From 160373a5e47bb4073d3f7ead040cd38b024fbfb0 Mon Sep 17 00:00:00 2001 From: Cloud SDK Librarian Date: Wed, 8 Apr 2026 07:08:52 +0000 Subject: [PATCH] feat: generate libraries --- .librarian/state.yaml | 46 +- .../google/apps/chat/__init__.py | 28 + .../google/apps/chat_v1/__init__.py | 28 + .../google/apps/chat_v1/gapic_metadata.json | 105 + .../services/chat_service/async_client.py | 970 +- .../chat_v1/services/chat_service/client.py | 997 +- .../chat_v1/services/chat_service/pagers.py | 321 +- .../services/chat_service/transports/base.py | 174 + .../services/chat_service/transports/grpc.py | 283 +- .../chat_service/transports/grpc_asyncio.py | 389 +- .../services/chat_service/transports/rest.py | 1670 +- .../chat_service/transports/rest_base.py | 373 + .../google/apps/chat_v1/types/__init__.py | 28 + .../google/apps/chat_v1/types/section.py | 523 + ...rated_chat_service_create_section_async.py | 57 + ...erated_chat_service_create_section_sync.py | 57 + ...rated_chat_service_delete_section_async.py | 50 + ...erated_chat_service_delete_section_sync.py | 50 + ...d_chat_service_list_section_items_async.py | 54 + ...ed_chat_service_list_section_items_sync.py | 54 + ...erated_chat_service_list_sections_async.py | 54 + ...nerated_chat_service_list_sections_sync.py | 54 + ...ed_chat_service_move_section_item_async.py | 54 + ...ted_chat_service_move_section_item_sync.py | 54 + ...ted_chat_service_position_section_async.py | 54 + ...ated_chat_service_position_section_sync.py | 54 + ...rated_chat_service_update_section_async.py | 56 + ...erated_chat_service_update_section_sync.py | 56 + .../snippet_metadata_google.chat.v1.json | 1419 +- .../unit/gapic/chat_v1/test_chat_service.py | 17329 ++++++++++------ .../google/cloud/dlp/__init__.py | 4 + .../google/cloud/dlp_v2/__init__.py | 4 + .../google/cloud/dlp_v2/types/__init__.py | 4 + .../google/cloud/dlp_v2/types/dlp.py | 48 + .../cloud/memorystore_v1beta/__init__.py | 4 + .../memorystore_v1beta/gapic_metadata.json | 5 + .../services/memorystore/client.py | 159 + .../services/memorystore/transports/base.py | 17 + .../services/memorystore/transports/rest.py | 232 + .../memorystore/transports/rest_base.py | 49 + .../memorystore_v1beta/types/__init__.py | 4 + .../memorystore_v1beta/types/memorystore.py | 146 + ...red_regional_certificate_authority_sync.py | 53 + ...adata_google.cloud.memorystore.v1beta.json | 80 + .../memorystore_v1beta/test_memorystore.py | 509 +- .../google/pubsub_v1/types/pubsub.py | 2 +- .../google/cloud/_storage_v2/types/storage.py | 29 +- .../cloud/translate_v3/types/adaptive_mt.py | 6 + .../translate_v3/test_translation_service.py | 2 + 49 files changed, 20599 insertions(+), 6199 deletions(-) create mode 100644 packages/google-apps-chat/google/apps/chat_v1/types/section.py create mode 100644 packages/google-apps-chat/samples/generated_samples/chat_v1_generated_chat_service_create_section_async.py create mode 100644 packages/google-apps-chat/samples/generated_samples/chat_v1_generated_chat_service_create_section_sync.py create mode 100644 packages/google-apps-chat/samples/generated_samples/chat_v1_generated_chat_service_delete_section_async.py create mode 100644 packages/google-apps-chat/samples/generated_samples/chat_v1_generated_chat_service_delete_section_sync.py create mode 100644 packages/google-apps-chat/samples/generated_samples/chat_v1_generated_chat_service_list_section_items_async.py create mode 100644 packages/google-apps-chat/samples/generated_samples/chat_v1_generated_chat_service_list_section_items_sync.py create mode 100644 packages/google-apps-chat/samples/generated_samples/chat_v1_generated_chat_service_list_sections_async.py create mode 100644 packages/google-apps-chat/samples/generated_samples/chat_v1_generated_chat_service_list_sections_sync.py create mode 100644 packages/google-apps-chat/samples/generated_samples/chat_v1_generated_chat_service_move_section_item_async.py create mode 100644 packages/google-apps-chat/samples/generated_samples/chat_v1_generated_chat_service_move_section_item_sync.py create mode 100644 packages/google-apps-chat/samples/generated_samples/chat_v1_generated_chat_service_position_section_async.py create mode 100644 packages/google-apps-chat/samples/generated_samples/chat_v1_generated_chat_service_position_section_sync.py create mode 100644 packages/google-apps-chat/samples/generated_samples/chat_v1_generated_chat_service_update_section_async.py create mode 100644 packages/google-apps-chat/samples/generated_samples/chat_v1_generated_chat_service_update_section_sync.py create mode 100644 packages/google-cloud-memorystore/samples/generated_samples/memorystore_v1beta_generated_memorystore_get_shared_regional_certificate_authority_sync.py diff --git a/.librarian/state.yaml b/.librarian/state.yaml index bd39d2a7c0a4..eaf3e52cb76d 100644 --- a/.librarian/state.yaml +++ b/.librarian/state.yaml @@ -1,3 +1,16 @@ +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. image: us-central1-docker.pkg.dev/cloud-sdk-librarian-prod/images-prod/python-librarian-generator@sha256:234b9d1f2ddb057ed7ac6a38db0bf8163d839c65c6cf88ade52530cddebce59e libraries: - id: bigframes @@ -164,7 +177,6 @@ libraries: last_generated_commit: 7a5706618f42f482acf583febcc7b977b66c25b2 apis: - path: google/apps/card/v1 - service_config: "" source_roots: - packages/google-apps-card preserve_regex: @@ -176,7 +188,7 @@ libraries: tag_format: '{id}-v{version}' - id: google-apps-chat version: 0.7.0 - last_generated_commit: 7a5706618f42f482acf583febcc7b977b66c25b2 + last_generated_commit: 2233f63baf69c2a481f30180045fcf036242781d apis: - path: google/chat/v1 service_config: chat_v1.yaml @@ -225,19 +237,12 @@ libraries: last_generated_commit: 3322511885371d2b2253f209ccc3aa60d4100cfd apis: - path: google/apps/script/type - service_config: "" - path: google/apps/script/type/gmail - service_config: "" - path: google/apps/script/type/docs - service_config: "" - path: google/apps/script/type/drive - service_config: "" - path: google/apps/script/type/sheets - service_config: "" - path: google/apps/script/type/calendar - service_config: "" - path: google/apps/script/type/slides - service_config: "" source_roots: - packages/google-apps-script-type preserve_regex: @@ -316,7 +321,6 @@ libraries: - path: google/identity/accesscontextmanager/v1 service_config: accesscontextmanager_v1.yaml - path: google/identity/accesscontextmanager/type - service_config: "" source_roots: - packages/google-cloud-access-context-manager preserve_regex: [] @@ -484,7 +488,6 @@ libraries: last_generated_commit: 3322511885371d2b2253f209ccc3aa60d4100cfd apis: - path: google/appengine/logging/v1 - service_config: "" source_roots: - packages/google-cloud-appengine-logging preserve_regex: @@ -869,7 +872,6 @@ libraries: last_generated_commit: 3322511885371d2b2253f209ccc3aa60d4100cfd apis: - path: google/cloud/bigquery/logging/v1 - service_config: "" source_roots: - packages/google-cloud-bigquery-logging preserve_regex: @@ -1657,7 +1659,7 @@ libraries: tag_format: '{id}-v{version}' - id: google-cloud-dlp version: 3.35.0 - last_generated_commit: 59d5f2b46924714af627ac29ea6de78641a00835 + last_generated_commit: 2233f63baf69c2a481f30180045fcf036242781d apis: - path: google/privacy/dlp/v2 service_config: dlp_v2.yaml @@ -1890,7 +1892,6 @@ libraries: - path: google/firestore/admin/v1 service_config: firestore_v1.yaml - path: google/firestore/bundle - service_config: "" - path: google/firestore/v1 service_config: firestore_v1.yaml source_roots: @@ -2130,7 +2131,6 @@ libraries: last_generated_commit: 3322511885371d2b2253f209ccc3aa60d4100cfd apis: - path: google/iam/v1/logging - service_config: "" source_roots: - packages/google-cloud-iam-logging preserve_regex: @@ -2424,7 +2424,7 @@ libraries: tag_format: '{id}-v{version}' - id: google-cloud-memorystore version: 0.4.0 - last_generated_commit: 582172de2d9b6443e1fecf696167867c6d8a5fc4 + last_generated_commit: 2233f63baf69c2a481f30180045fcf036242781d apis: - path: google/cloud/memorystore/v1beta service_config: memorystore_v1beta.yaml @@ -2672,7 +2672,6 @@ libraries: last_generated_commit: 55319b058f8a0e46bbeeff30e374e4b1f081f494 apis: - path: google/cloud/orgpolicy/v1 - service_config: "" - path: google/cloud/orgpolicy/v2 service_config: orgpolicy_v2.yaml source_roots: @@ -2851,7 +2850,7 @@ libraries: tag_format: '{id}-v{version}' - id: google-cloud-pubsub version: 2.36.0 - last_generated_commit: 256b575f6915282b20795c13414b21f2c0af65db + last_generated_commit: 2233f63baf69c2a481f30180045fcf036242781d apis: - path: google/pubsub/v1 service_config: pubsub_v1.yaml @@ -3252,7 +3251,6 @@ libraries: last_generated_commit: 3322511885371d2b2253f209ccc3aa60d4100cfd apis: - path: google/devtools/source/v1 - service_config: "" source_roots: - packages/google-cloud-source-context preserve_regex: @@ -3367,7 +3365,7 @@ libraries: tag_format: '{id}-v{version}' - id: google-cloud-storage version: 3.10.1 - last_generated_commit: 280bed6c219637610d09cebf696958dd99fd2f76 + last_generated_commit: 2233f63baf69c2a481f30180045fcf036242781d apis: - path: google/storage/v2 service_config: storage_v2.yaml @@ -3588,7 +3586,7 @@ libraries: tag_format: '{id}-v{version}' - id: google-cloud-translate version: 3.25.0 - last_generated_commit: 6df3ecf4fd43b64826de6a477d1a535ec18b0d7c + last_generated_commit: 2233f63baf69c2a481f30180045fcf036242781d apis: - path: google/cloud/translate/v3beta1 service_config: translate_v3beta1.yaml @@ -4296,7 +4294,6 @@ libraries: last_generated_commit: 6df3ecf4fd43b64826de6a477d1a535ec18b0d7c apis: - path: google/shopping/type - service_config: "" source_roots: - packages/google-shopping-type preserve_regex: @@ -4308,20 +4305,17 @@ libraries: tag_format: '{id}-v{version}' - id: googleapis-common-protos version: 1.74.0 - last_generated_commit: 582172de2d9b6443e1fecf696167867c6d8a5fc4 + last_generated_commit: 2233f63baf69c2a481f30180045fcf036242781d apis: - path: google/api service_config: serviceconfig.yaml - path: google/cloud - service_config: "" - path: google/cloud/location service_config: cloud.yaml - path: google/logging/type - service_config: "" - path: google/rpc service_config: rpc_publish.yaml - path: google/rpc/context - service_config: "" - path: google/type service_config: type.yaml source_roots: diff --git a/packages/google-apps-chat/google/apps/chat/__init__.py b/packages/google-apps-chat/google/apps/chat/__init__.py index 453874ad0db6..4f472be4866c 100644 --- a/packages/google-apps-chat/google/apps/chat/__init__.py +++ b/packages/google-apps-chat/google/apps/chat/__init__.py @@ -111,6 +111,21 @@ ListReactionsResponse, Reaction, ) +from google.apps.chat_v1.types.section import ( + CreateSectionRequest, + DeleteSectionRequest, + ListSectionItemsRequest, + ListSectionItemsResponse, + ListSectionsRequest, + ListSectionsResponse, + MoveSectionItemRequest, + MoveSectionItemResponse, + PositionSectionRequest, + PositionSectionResponse, + Section, + SectionItem, + UpdateSectionRequest, +) from google.apps.chat_v1.types.slash_command import SlashCommand from google.apps.chat_v1.types.space import ( CompleteImportSpaceRequest, @@ -230,6 +245,19 @@ "ListReactionsRequest", "ListReactionsResponse", "Reaction", + "CreateSectionRequest", + "DeleteSectionRequest", + "ListSectionItemsRequest", + "ListSectionItemsResponse", + "ListSectionsRequest", + "ListSectionsResponse", + "MoveSectionItemRequest", + "MoveSectionItemResponse", + "PositionSectionRequest", + "PositionSectionResponse", + "Section", + "SectionItem", + "UpdateSectionRequest", "SlashCommand", "CompleteImportSpaceRequest", "CompleteImportSpaceResponse", 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 cd6270ac6cd6..8faf4e22479c 100644 --- a/packages/google-apps-chat/google/apps/chat_v1/__init__.py +++ b/packages/google-apps-chat/google/apps/chat_v1/__init__.py @@ -119,6 +119,21 @@ ListReactionsResponse, Reaction, ) +from .types.section import ( + CreateSectionRequest, + DeleteSectionRequest, + ListSectionItemsRequest, + ListSectionItemsResponse, + ListSectionsRequest, + ListSectionsResponse, + MoveSectionItemRequest, + MoveSectionItemResponse, + PositionSectionRequest, + PositionSectionResponse, + Section, + SectionItem, + UpdateSectionRequest, +) from .types.slash_command import SlashCommand from .types.space import ( CompleteImportSpaceRequest, @@ -270,6 +285,7 @@ def _get_version(dependency_name): "CreateMembershipRequest", "CreateMessageRequest", "CreateReactionRequest", + "CreateSectionRequest", "CreateSpaceRequest", "CustomEmoji", "CustomEmojiMetadata", @@ -277,6 +293,7 @@ def _get_version(dependency_name): "DeleteMembershipRequest", "DeleteMessageRequest", "DeleteReactionRequest", + "DeleteSectionRequest", "DeleteSpaceRequest", "DeletionMetadata", "Dialog", @@ -306,6 +323,10 @@ def _get_version(dependency_name): "ListMessagesResponse", "ListReactionsRequest", "ListReactionsResponse", + "ListSectionItemsRequest", + "ListSectionItemsResponse", + "ListSectionsRequest", + "ListSectionsResponse", "ListSpaceEventsRequest", "ListSpaceEventsResponse", "ListSpacesRequest", @@ -326,6 +347,10 @@ def _get_version(dependency_name): "MessageCreatedEventData", "MessageDeletedEventData", "MessageUpdatedEventData", + "MoveSectionItemRequest", + "MoveSectionItemResponse", + "PositionSectionRequest", + "PositionSectionResponse", "QuotedMessageMetadata", "QuotedMessageSnapshot", "Reaction", @@ -336,6 +361,8 @@ def _get_version(dependency_name): "RichLinkMetadata", "SearchSpacesRequest", "SearchSpacesResponse", + "Section", + "SectionItem", "SetUpSpaceRequest", "SlashCommand", "SlashCommandMetadata", @@ -349,6 +376,7 @@ def _get_version(dependency_name): "ThreadReadState", "UpdateMembershipRequest", "UpdateMessageRequest", + "UpdateSectionRequest", "UpdateSpaceNotificationSettingRequest", "UpdateSpaceReadStateRequest", "UpdateSpaceRequest", diff --git a/packages/google-apps-chat/google/apps/chat_v1/gapic_metadata.json b/packages/google-apps-chat/google/apps/chat_v1/gapic_metadata.json index 5df6c90f6825..7cdaf7f91975 100644 --- a/packages/google-apps-chat/google/apps/chat_v1/gapic_metadata.json +++ b/packages/google-apps-chat/google/apps/chat_v1/gapic_metadata.json @@ -35,6 +35,11 @@ "create_reaction" ] }, + "CreateSection": { + "methods": [ + "create_section" + ] + }, "CreateSpace": { "methods": [ "create_space" @@ -60,6 +65,11 @@ "delete_reaction" ] }, + "DeleteSection": { + "methods": [ + "delete_section" + ] + }, "DeleteSpace": { "methods": [ "delete_space" @@ -135,6 +145,16 @@ "list_reactions" ] }, + "ListSectionItems": { + "methods": [ + "list_section_items" + ] + }, + "ListSections": { + "methods": [ + "list_sections" + ] + }, "ListSpaceEvents": { "methods": [ "list_space_events" @@ -145,6 +165,16 @@ "list_spaces" ] }, + "MoveSectionItem": { + "methods": [ + "move_section_item" + ] + }, + "PositionSection": { + "methods": [ + "position_section" + ] + }, "SearchSpaces": { "methods": [ "search_spaces" @@ -165,6 +195,11 @@ "update_message" ] }, + "UpdateSection": { + "methods": [ + "update_section" + ] + }, "UpdateSpace": { "methods": [ "update_space" @@ -215,6 +250,11 @@ "create_reaction" ] }, + "CreateSection": { + "methods": [ + "create_section" + ] + }, "CreateSpace": { "methods": [ "create_space" @@ -240,6 +280,11 @@ "delete_reaction" ] }, + "DeleteSection": { + "methods": [ + "delete_section" + ] + }, "DeleteSpace": { "methods": [ "delete_space" @@ -315,6 +360,16 @@ "list_reactions" ] }, + "ListSectionItems": { + "methods": [ + "list_section_items" + ] + }, + "ListSections": { + "methods": [ + "list_sections" + ] + }, "ListSpaceEvents": { "methods": [ "list_space_events" @@ -325,6 +380,16 @@ "list_spaces" ] }, + "MoveSectionItem": { + "methods": [ + "move_section_item" + ] + }, + "PositionSection": { + "methods": [ + "position_section" + ] + }, "SearchSpaces": { "methods": [ "search_spaces" @@ -345,6 +410,11 @@ "update_message" ] }, + "UpdateSection": { + "methods": [ + "update_section" + ] + }, "UpdateSpace": { "methods": [ "update_space" @@ -395,6 +465,11 @@ "create_reaction" ] }, + "CreateSection": { + "methods": [ + "create_section" + ] + }, "CreateSpace": { "methods": [ "create_space" @@ -420,6 +495,11 @@ "delete_reaction" ] }, + "DeleteSection": { + "methods": [ + "delete_section" + ] + }, "DeleteSpace": { "methods": [ "delete_space" @@ -495,6 +575,16 @@ "list_reactions" ] }, + "ListSectionItems": { + "methods": [ + "list_section_items" + ] + }, + "ListSections": { + "methods": [ + "list_sections" + ] + }, "ListSpaceEvents": { "methods": [ "list_space_events" @@ -505,6 +595,16 @@ "list_spaces" ] }, + "MoveSectionItem": { + "methods": [ + "move_section_item" + ] + }, + "PositionSection": { + "methods": [ + "position_section" + ] + }, "SearchSpaces": { "methods": [ "search_spaces" @@ -525,6 +625,11 @@ "update_message" ] }, + "UpdateSection": { + "methods": [ + "update_section" + ] + }, "UpdateSpace": { "methods": [ "update_space" 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 1f16c255dca5..646b04bb490f 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 @@ -60,6 +60,7 @@ membership, message, reaction, + section, slash_command, space, space_event, @@ -72,6 +73,7 @@ from google.apps.chat_v1.types import membership as gc_membership from google.apps.chat_v1.types import message as gc_message from google.apps.chat_v1.types import reaction as gc_reaction +from google.apps.chat_v1.types import section as gc_section from google.apps.chat_v1.types import space as gc_space from google.apps.chat_v1.types import ( space_notification_setting as gc_space_notification_setting, @@ -122,6 +124,10 @@ class ChatServiceAsyncClient: ) reaction_path = staticmethod(ChatServiceClient.reaction_path) parse_reaction_path = staticmethod(ChatServiceClient.parse_reaction_path) + section_path = staticmethod(ChatServiceClient.section_path) + parse_section_path = staticmethod(ChatServiceClient.parse_section_path) + section_item_path = staticmethod(ChatServiceClient.section_item_path) + parse_section_item_path = staticmethod(ChatServiceClient.parse_section_item_path) space_path = staticmethod(ChatServiceClient.space_path) parse_space_path = staticmethod(ChatServiceClient.parse_space_path) space_event_path = staticmethod(ChatServiceClient.space_event_path) @@ -142,6 +148,8 @@ class ChatServiceAsyncClient: parse_thread_read_state_path = staticmethod( ChatServiceClient.parse_thread_read_state_path ) + user_path = staticmethod(ChatServiceClient.user_path) + parse_user_path = staticmethod(ChatServiceClient.parse_user_path) common_billing_account_path = staticmethod( ChatServiceClient.common_billing_account_path ) @@ -575,9 +583,7 @@ async def list_messages( - `App authentication `__ with `administrator - approval `__ in - `Developer - Preview `__ + approval `__ with the authorization scope: - ``https://www.googleapis.com/auth/chat.app.messages.readonly``. @@ -1059,9 +1065,7 @@ async def get_message( that invoke the Chat app. - ``https://www.googleapis.com/auth/chat.app.messages.readonly`` with `administrator - approval `__ - (available in `Developer - Preview `__). + approval `__. When using this authentication scope, this method returns details about a public message in a space. @@ -4835,14 +4839,14 @@ async def get_space_event( - `App authentication `__ with `administrator - approval `__ in - `Developer - Preview `__ + approval `__ with one of the following authorization scopes: - ``https://www.googleapis.com/auth/chat.app.spaces`` + - ``https://www.googleapis.com/auth/chat.app.spaces.readonly`` - ``https://www.googleapis.com/auth/chat.app.messages.readonly`` - ``https://www.googleapis.com/auth/chat.app.memberships`` + - ``https://www.googleapis.com/auth/chat.app.memberships.readonly`` - `User authentication `__ @@ -4994,14 +4998,14 @@ async def list_space_events( - `App authentication `__ with `administrator - approval `__ in - `Developer - Preview `__ + approval `__ with one of the following authorization scopes: - ``https://www.googleapis.com/auth/chat.app.spaces`` + - ``https://www.googleapis.com/auth/chat.app.spaces.readonly`` - ``https://www.googleapis.com/auth/chat.app.messages.readonly`` - ``https://www.googleapis.com/auth/chat.app.memberships`` + - ``https://www.googleapis.com/auth/chat.app.memberships.readonly`` - `User authentication `__ @@ -5499,6 +5503,948 @@ async def sample_update_space_notification_setting(): # Done; return the response. return response + async def create_section( + self, + request: Optional[Union[gc_section.CreateSectionRequest, dict]] = None, + *, + parent: Optional[str] = None, + section: Optional[gc_section.Section] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> gc_section.Section: + r"""Creates a section in Google Chat. Sections help users group + conversations and customize the list of spaces displayed in Chat + navigation panel. Only sections of type ``CUSTOM_SECTION`` can + be created. For details, see `Create and organize sections in + Google + Chat `__. + + Requires `user + authentication `__ + with the `authorization + scope `__: + + - ``https://www.googleapis.com/auth/chat.users.sections`` + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.apps import chat_v1 + + async def sample_create_section(): + # Create a client + client = chat_v1.ChatServiceAsyncClient() + + # Initialize request argument(s) + section = chat_v1.Section() + section.type_ = "DEFAULT_APPS" + + request = chat_v1.CreateSectionRequest( + parent="parent_value", + section=section, + ) + + # Make the request + response = await client.create_section(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.apps.chat_v1.types.CreateSectionRequest, dict]]): + The request object. Request message for creating a + section. + parent (:class:`str`): + Required. The parent resource name where the section is + created. + + Format: ``users/{user}`` + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + section (:class:`google.apps.chat_v1.types.Section`): + Required. The section to create. + This corresponds to the ``section`` 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.apps.chat_v1.types.Section: + Represents a [section](https://support.google.com/chat/answer/16059854) in + Google Chat. Sections help users organize their + spaces. There are two types of sections: + + 1. **System Sections:** These are predefined sections + managed by Google Chat. Their resource names are + fixed, and they cannot be created, deleted, or have + their display_name modified. Examples include: \* + users/{user}/sections/default-direct-messages \* + users/{user}/sections/default-spaces \* + users/{user}/sections/default-apps + + 2. **Custom Sections:** These are sections created + and managed by the user. Creating a custom section + using CreateSection **requires** a display_name. + Custom sections can be updated using UpdateSection + and deleted using DeleteSection. + + """ + # Create or coerce a protobuf request 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, section] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, gc_section.CreateSectionRequest): + request = gc_section.CreateSectionRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if section is not None: + request.section = section + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.create_section + ] + + # 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_section( + self, + request: Optional[Union[section.DeleteSectionRequest, 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 section of type ``CUSTOM_SECTION``. + + If the section contains items, such as spaces, the items are + moved to Google Chat's default sections and are not deleted. + + For details, see `Create and organize sections in Google + Chat `__. + + Requires `user + authentication `__ + with the `authorization + scope `__: + + - ``https://www.googleapis.com/auth/chat.users.sections`` + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.apps import chat_v1 + + async def sample_delete_section(): + # Create a client + client = chat_v1.ChatServiceAsyncClient() + + # Initialize request argument(s) + request = chat_v1.DeleteSectionRequest( + name="name_value", + ) + + # Make the request + await client.delete_section(request=request) + + Args: + request (Optional[Union[google.apps.chat_v1.types.DeleteSectionRequest, dict]]): + The request object. Request message for deleting a section. `Developer + Preview `__. + name (:class:`str`): + Required. The name of the section to delete. + + Format: ``users/{user}/sections/{section}`` + + 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, section.DeleteSectionRequest): + request = section.DeleteSectionRequest(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_section + ] + + # 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_section( + self, + request: Optional[Union[gc_section.UpdateSectionRequest, dict]] = None, + *, + section: Optional[gc_section.Section] = 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]]] = (), + ) -> gc_section.Section: + r"""Updates a section. Only sections of type ``CUSTOM_SECTION`` can + be updated. For details, see `Create and organize sections in + Google + Chat `__. + + Requires `user + authentication `__ + with the `authorization + scope `__: + + - ``https://www.googleapis.com/auth/chat.users.sections`` + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.apps import chat_v1 + + async def sample_update_section(): + # Create a client + client = chat_v1.ChatServiceAsyncClient() + + # Initialize request argument(s) + section = chat_v1.Section() + section.type_ = "DEFAULT_APPS" + + request = chat_v1.UpdateSectionRequest( + section=section, + ) + + # Make the request + response = await client.update_section(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.apps.chat_v1.types.UpdateSectionRequest, dict]]): + The request object. Request message for updating a + section. + section (:class:`google.apps.chat_v1.types.Section`): + Required. The section to update. + This corresponds to the ``section`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + Required. The mask to specify which fields to update. + + Currently supported field paths: + + - ``display_name`` + + 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.apps.chat_v1.types.Section: + Represents a [section](https://support.google.com/chat/answer/16059854) in + Google Chat. Sections help users organize their + spaces. There are two types of sections: + + 1. **System Sections:** These are predefined sections + managed by Google Chat. Their resource names are + fixed, and they cannot be created, deleted, or have + their display_name modified. Examples include: \* + users/{user}/sections/default-direct-messages \* + users/{user}/sections/default-spaces \* + users/{user}/sections/default-apps + + 2. **Custom Sections:** These are sections created + and managed by the user. Creating a custom section + using CreateSection **requires** a display_name. + Custom sections can be updated using UpdateSection + and deleted using DeleteSection. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [section, 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, gc_section.UpdateSectionRequest): + request = gc_section.UpdateSectionRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if section is not None: + request.section = section + 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_section + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("section.name", request.section.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_sections( + self, + request: Optional[Union[section.ListSectionsRequest, 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.ListSectionsAsyncPager: + r"""Lists sections available to the Chat user. Sections help users + group their conversations and customize the list of spaces + displayed in Chat navigation panel. For details, see `Create and + organize sections in Google + Chat `__. + + Requires `user + authentication `__ + with the `authorization + scope `__: + + - ``https://www.googleapis.com/auth/chat.users.sections`` + - ``https://www.googleapis.com/auth/chat.users.sections.readonly`` + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.apps import chat_v1 + + async def sample_list_sections(): + # Create a client + client = chat_v1.ChatServiceAsyncClient() + + # Initialize request argument(s) + request = chat_v1.ListSectionsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_sections(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.apps.chat_v1.types.ListSectionsRequest, dict]]): + The request object. Request message for listing sections. + parent (:class:`str`): + Required. The parent, which is the user resource name + that owns this collection of sections. Only supports + listing sections for the calling user. To refer to the + calling user, set one of the following: + + - The ``me`` alias. For example, ``users/me``. + + - Their Workspace email address. For example, + ``users/user@example.com``. + + - Their user id. For example, ``users/123456789``. + + Format: ``users/{user}`` + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.apps.chat_v1.services.chat_service.pagers.ListSectionsAsyncPager: + Response message for listing + sections. + 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, section.ListSectionsRequest): + request = section.ListSectionsRequest(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_sections + ] + + # 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.ListSectionsAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def position_section( + self, + request: Optional[Union[section.PositionSectionRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> section.PositionSectionResponse: + r"""Changes the sort order of a section. For details, see `Create + and organize sections in Google + Chat `__. + + Requires `user + authentication `__ + with the `authorization + scope `__: + + - ``https://www.googleapis.com/auth/chat.users.sections`` + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.apps import chat_v1 + + async def sample_position_section(): + # Create a client + client = chat_v1.ChatServiceAsyncClient() + + # Initialize request argument(s) + request = chat_v1.PositionSectionRequest( + sort_order=1091, + name="name_value", + ) + + # Make the request + response = await client.position_section(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.apps.chat_v1.types.PositionSectionRequest, dict]]): + The request object. Request message for positioning a + section. + 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.apps.chat_v1.types.PositionSectionResponse: + Response message for positioning a + section. + + """ + # 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, section.PositionSectionRequest): + request = section.PositionSectionRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.position_section + ] + + # 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_section_items( + self, + request: Optional[Union[section.ListSectionItemsRequest, 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.ListSectionItemsAsyncPager: + r"""Lists items in a section. + + Only spaces can be section items. For details, see `Create and + organize sections in Google + Chat `__. + + Requires `user + authentication `__ + with the `authorization + scope `__: + + - ``https://www.googleapis.com/auth/chat.users.sections`` + - ``https://www.googleapis.com/auth/chat.users.sections.readonly`` + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.apps import chat_v1 + + async def sample_list_section_items(): + # Create a client + client = chat_v1.ChatServiceAsyncClient() + + # Initialize request argument(s) + request = chat_v1.ListSectionItemsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_section_items(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.apps.chat_v1.types.ListSectionItemsRequest, dict]]): + The request object. Request message for listing section + items. + parent (:class:`str`): + Required. The parent, which is the section resource name + that owns this collection of section items. Only + supports listing section items for the calling user. + + When you're filtering by space, use the wildcard ``-`` + to search across all sections. For example, + ``users/{user}/sections/-``. + + Format: ``users/{user}/sections/{section}`` + + 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.apps.chat_v1.services.chat_service.pagers.ListSectionItemsAsyncPager: + Response message for listing section + items. + 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, section.ListSectionItemsRequest): + request = section.ListSectionItemsRequest(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_section_items + ] + + # 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.ListSectionItemsAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def move_section_item( + self, + request: Optional[Union[section.MoveSectionItemRequest, dict]] = None, + *, + name: Optional[str] = None, + target_section: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> section.MoveSectionItemResponse: + r"""Moves an item from one section to another. For example, if a + section contains spaces, this method can be used to move a space + to a different section. For details, see `Create and organize + sections in Google + Chat `__. + + Requires `user + authentication `__ + with the `authorization + scope `__: + + - ``https://www.googleapis.com/auth/chat.users.sections`` + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.apps import chat_v1 + + async def sample_move_section_item(): + # Create a client + client = chat_v1.ChatServiceAsyncClient() + + # Initialize request argument(s) + request = chat_v1.MoveSectionItemRequest( + name="name_value", + target_section="target_section_value", + ) + + # Make the request + response = await client.move_section_item(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.apps.chat_v1.types.MoveSectionItemRequest, dict]]): + The request object. Request message for moving a section + item across sections. + name (:class:`str`): + Required. The resource name of the section item to move. + + Format: ``users/{user}/sections/{section}/items/{item}`` + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + target_section (:class:`str`): + Required. The resource name of the section to move the + section item to. + + Format: ``users/{user}/sections/{section}`` + + This corresponds to the ``target_section`` 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.apps.chat_v1.types.MoveSectionItemResponse: + Response message for moving a section + item. + + """ + # Create or coerce a protobuf request 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, target_section] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, section.MoveSectionItemRequest): + request = section.MoveSectionItemRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + if target_section is not None: + request.target_section = target_section + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.move_section_item + ] + + # 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 __aenter__(self) -> "ChatServiceAsyncClient": return self 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 3bc454149959..147fe44be01c 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 @@ -77,6 +77,7 @@ membership, message, reaction, + section, slash_command, space, space_event, @@ -89,6 +90,7 @@ from google.apps.chat_v1.types import membership as gc_membership from google.apps.chat_v1.types import message as gc_message from google.apps.chat_v1.types import reaction as gc_reaction +from google.apps.chat_v1.types import section as gc_section from google.apps.chat_v1.types import space as gc_space from google.apps.chat_v1.types import ( space_notification_setting as gc_space_notification_setting, @@ -374,6 +376,44 @@ def parse_reaction_path(path: str) -> Dict[str, str]: ) return m.groupdict() if m else {} + @staticmethod + def section_path( + user: str, + section: str, + ) -> str: + """Returns a fully-qualified section string.""" + return "users/{user}/sections/{section}".format( + user=user, + section=section, + ) + + @staticmethod + def parse_section_path(path: str) -> Dict[str, str]: + """Parses a section path into its component segments.""" + m = re.match(r"^users/(?P.+?)/sections/(?P
.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def section_item_path( + user: str, + section: str, + item: str, + ) -> str: + """Returns a fully-qualified section_item string.""" + return "users/{user}/sections/{section}/items/{item}".format( + user=user, + section=section, + item=item, + ) + + @staticmethod + def parse_section_item_path(path: str) -> Dict[str, str]: + """Parses a section_item path into its component segments.""" + m = re.match( + r"^users/(?P.+?)/sections/(?P
.+?)/items/(?P.+?)$", path + ) + return m.groupdict() if m else {} + @staticmethod def space_path( space: str, @@ -484,6 +524,21 @@ def parse_thread_read_state_path(path: str) -> Dict[str, str]: ) return m.groupdict() if m else {} + @staticmethod + def user_path( + user: str, + ) -> str: + """Returns a fully-qualified user string.""" + return "users/{user}".format( + user=user, + ) + + @staticmethod + def parse_user_path(path: str) -> Dict[str, str]: + """Parses a user path into its component segments.""" + m = re.match(r"^users/(?P.+?)$", path) + return m.groupdict() if m else {} + @staticmethod def common_billing_account_path( billing_account: str, @@ -1176,9 +1231,7 @@ def list_messages( - `App authentication `__ with `administrator - approval `__ in - `Developer - Preview `__ + approval `__ with the authorization scope: - ``https://www.googleapis.com/auth/chat.app.messages.readonly``. @@ -1651,9 +1704,7 @@ def get_message( that invoke the Chat app. - ``https://www.googleapis.com/auth/chat.app.messages.readonly`` with `administrator - approval `__ - (available in `Developer - Preview `__). + approval `__. When using this authentication scope, this method returns details about a public message in a space. @@ -5353,14 +5404,14 @@ def get_space_event( - `App authentication `__ with `administrator - approval `__ in - `Developer - Preview `__ + approval `__ with one of the following authorization scopes: - ``https://www.googleapis.com/auth/chat.app.spaces`` + - ``https://www.googleapis.com/auth/chat.app.spaces.readonly`` - ``https://www.googleapis.com/auth/chat.app.messages.readonly`` - ``https://www.googleapis.com/auth/chat.app.memberships`` + - ``https://www.googleapis.com/auth/chat.app.memberships.readonly`` - `User authentication `__ @@ -5509,14 +5560,14 @@ def list_space_events( - `App authentication `__ with `administrator - approval `__ in - `Developer - Preview `__ + approval `__ with one of the following authorization scopes: - ``https://www.googleapis.com/auth/chat.app.spaces`` + - ``https://www.googleapis.com/auth/chat.app.spaces.readonly`` - ``https://www.googleapis.com/auth/chat.app.messages.readonly`` - ``https://www.googleapis.com/auth/chat.app.memberships`` + - ``https://www.googleapis.com/auth/chat.app.memberships.readonly`` - `User authentication `__ @@ -6009,6 +6060,928 @@ def sample_update_space_notification_setting(): # Done; return the response. return response + def create_section( + self, + request: Optional[Union[gc_section.CreateSectionRequest, dict]] = None, + *, + parent: Optional[str] = None, + section: Optional[gc_section.Section] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> gc_section.Section: + r"""Creates a section in Google Chat. Sections help users group + conversations and customize the list of spaces displayed in Chat + navigation panel. Only sections of type ``CUSTOM_SECTION`` can + be created. For details, see `Create and organize sections in + Google + Chat `__. + + Requires `user + authentication `__ + with the `authorization + scope `__: + + - ``https://www.googleapis.com/auth/chat.users.sections`` + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.apps import chat_v1 + + def sample_create_section(): + # Create a client + client = chat_v1.ChatServiceClient() + + # Initialize request argument(s) + section = chat_v1.Section() + section.type_ = "DEFAULT_APPS" + + request = chat_v1.CreateSectionRequest( + parent="parent_value", + section=section, + ) + + # Make the request + response = client.create_section(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.apps.chat_v1.types.CreateSectionRequest, dict]): + The request object. Request message for creating a + section. + parent (str): + Required. The parent resource name where the section is + created. + + Format: ``users/{user}`` + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + section (google.apps.chat_v1.types.Section): + Required. The section to create. + This corresponds to the ``section`` 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.apps.chat_v1.types.Section: + Represents a [section](https://support.google.com/chat/answer/16059854) in + Google Chat. Sections help users organize their + spaces. There are two types of sections: + + 1. **System Sections:** These are predefined sections + managed by Google Chat. Their resource names are + fixed, and they cannot be created, deleted, or have + their display_name modified. Examples include: \* + users/{user}/sections/default-direct-messages \* + users/{user}/sections/default-spaces \* + users/{user}/sections/default-apps + + 2. **Custom Sections:** These are sections created + and managed by the user. Creating a custom section + using CreateSection **requires** a display_name. + Custom sections can be updated using UpdateSection + and deleted using DeleteSection. + + """ + # Create or coerce a protobuf request 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, section] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, gc_section.CreateSectionRequest): + request = gc_section.CreateSectionRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if section is not None: + request.section = section + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_section] + + # 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_section( + self, + request: Optional[Union[section.DeleteSectionRequest, 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 section of type ``CUSTOM_SECTION``. + + If the section contains items, such as spaces, the items are + moved to Google Chat's default sections and are not deleted. + + For details, see `Create and organize sections in Google + Chat `__. + + Requires `user + authentication `__ + with the `authorization + scope `__: + + - ``https://www.googleapis.com/auth/chat.users.sections`` + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.apps import chat_v1 + + def sample_delete_section(): + # Create a client + client = chat_v1.ChatServiceClient() + + # Initialize request argument(s) + request = chat_v1.DeleteSectionRequest( + name="name_value", + ) + + # Make the request + client.delete_section(request=request) + + Args: + request (Union[google.apps.chat_v1.types.DeleteSectionRequest, dict]): + The request object. Request message for deleting a section. `Developer + Preview `__. + name (str): + Required. The name of the section to delete. + + Format: ``users/{user}/sections/{section}`` + + 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, section.DeleteSectionRequest): + request = section.DeleteSectionRequest(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_section] + + # 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_section( + self, + request: Optional[Union[gc_section.UpdateSectionRequest, dict]] = None, + *, + section: Optional[gc_section.Section] = 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]]] = (), + ) -> gc_section.Section: + r"""Updates a section. Only sections of type ``CUSTOM_SECTION`` can + be updated. For details, see `Create and organize sections in + Google + Chat `__. + + Requires `user + authentication `__ + with the `authorization + scope `__: + + - ``https://www.googleapis.com/auth/chat.users.sections`` + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.apps import chat_v1 + + def sample_update_section(): + # Create a client + client = chat_v1.ChatServiceClient() + + # Initialize request argument(s) + section = chat_v1.Section() + section.type_ = "DEFAULT_APPS" + + request = chat_v1.UpdateSectionRequest( + section=section, + ) + + # Make the request + response = client.update_section(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.apps.chat_v1.types.UpdateSectionRequest, dict]): + The request object. Request message for updating a + section. + section (google.apps.chat_v1.types.Section): + Required. The section to update. + This corresponds to the ``section`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. The mask to specify which fields to update. + + Currently supported field paths: + + - ``display_name`` + + 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.apps.chat_v1.types.Section: + Represents a [section](https://support.google.com/chat/answer/16059854) in + Google Chat. Sections help users organize their + spaces. There are two types of sections: + + 1. **System Sections:** These are predefined sections + managed by Google Chat. Their resource names are + fixed, and they cannot be created, deleted, or have + their display_name modified. Examples include: \* + users/{user}/sections/default-direct-messages \* + users/{user}/sections/default-spaces \* + users/{user}/sections/default-apps + + 2. **Custom Sections:** These are sections created + and managed by the user. Creating a custom section + using CreateSection **requires** a display_name. + Custom sections can be updated using UpdateSection + and deleted using DeleteSection. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [section, 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, gc_section.UpdateSectionRequest): + request = gc_section.UpdateSectionRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if section is not None: + request.section = section + 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_section] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("section.name", request.section.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_sections( + self, + request: Optional[Union[section.ListSectionsRequest, 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.ListSectionsPager: + r"""Lists sections available to the Chat user. Sections help users + group their conversations and customize the list of spaces + displayed in Chat navigation panel. For details, see `Create and + organize sections in Google + Chat `__. + + Requires `user + authentication `__ + with the `authorization + scope `__: + + - ``https://www.googleapis.com/auth/chat.users.sections`` + - ``https://www.googleapis.com/auth/chat.users.sections.readonly`` + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.apps import chat_v1 + + def sample_list_sections(): + # Create a client + client = chat_v1.ChatServiceClient() + + # Initialize request argument(s) + request = chat_v1.ListSectionsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_sections(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.apps.chat_v1.types.ListSectionsRequest, dict]): + The request object. Request message for listing sections. + parent (str): + Required. The parent, which is the user resource name + that owns this collection of sections. Only supports + listing sections for the calling user. To refer to the + calling user, set one of the following: + + - The ``me`` alias. For example, ``users/me``. + + - Their Workspace email address. For example, + ``users/user@example.com``. + + - Their user id. For example, ``users/123456789``. + + Format: ``users/{user}`` + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.apps.chat_v1.services.chat_service.pagers.ListSectionsPager: + Response message for listing + sections. + 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, section.ListSectionsRequest): + request = section.ListSectionsRequest(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_sections] + + # 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.ListSectionsPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def position_section( + self, + request: Optional[Union[section.PositionSectionRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> section.PositionSectionResponse: + r"""Changes the sort order of a section. For details, see `Create + and organize sections in Google + Chat `__. + + Requires `user + authentication `__ + with the `authorization + scope `__: + + - ``https://www.googleapis.com/auth/chat.users.sections`` + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.apps import chat_v1 + + def sample_position_section(): + # Create a client + client = chat_v1.ChatServiceClient() + + # Initialize request argument(s) + request = chat_v1.PositionSectionRequest( + sort_order=1091, + name="name_value", + ) + + # Make the request + response = client.position_section(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.apps.chat_v1.types.PositionSectionRequest, dict]): + The request object. Request message for positioning a + section. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.apps.chat_v1.types.PositionSectionResponse: + Response message for positioning a + section. + + """ + # 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, section.PositionSectionRequest): + request = section.PositionSectionRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.position_section] + + # 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_section_items( + self, + request: Optional[Union[section.ListSectionItemsRequest, 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.ListSectionItemsPager: + r"""Lists items in a section. + + Only spaces can be section items. For details, see `Create and + organize sections in Google + Chat `__. + + Requires `user + authentication `__ + with the `authorization + scope `__: + + - ``https://www.googleapis.com/auth/chat.users.sections`` + - ``https://www.googleapis.com/auth/chat.users.sections.readonly`` + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.apps import chat_v1 + + def sample_list_section_items(): + # Create a client + client = chat_v1.ChatServiceClient() + + # Initialize request argument(s) + request = chat_v1.ListSectionItemsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_section_items(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.apps.chat_v1.types.ListSectionItemsRequest, dict]): + The request object. Request message for listing section + items. + parent (str): + Required. The parent, which is the section resource name + that owns this collection of section items. Only + supports listing section items for the calling user. + + When you're filtering by space, use the wildcard ``-`` + to search across all sections. For example, + ``users/{user}/sections/-``. + + Format: ``users/{user}/sections/{section}`` + + 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.apps.chat_v1.services.chat_service.pagers.ListSectionItemsPager: + Response message for listing section + items. + 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, section.ListSectionItemsRequest): + request = section.ListSectionItemsRequest(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_section_items] + + # 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.ListSectionItemsPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def move_section_item( + self, + request: Optional[Union[section.MoveSectionItemRequest, dict]] = None, + *, + name: Optional[str] = None, + target_section: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> section.MoveSectionItemResponse: + r"""Moves an item from one section to another. For example, if a + section contains spaces, this method can be used to move a space + to a different section. For details, see `Create and organize + sections in Google + Chat `__. + + Requires `user + authentication `__ + with the `authorization + scope `__: + + - ``https://www.googleapis.com/auth/chat.users.sections`` + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.apps import chat_v1 + + def sample_move_section_item(): + # Create a client + client = chat_v1.ChatServiceClient() + + # Initialize request argument(s) + request = chat_v1.MoveSectionItemRequest( + name="name_value", + target_section="target_section_value", + ) + + # Make the request + response = client.move_section_item(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.apps.chat_v1.types.MoveSectionItemRequest, dict]): + The request object. Request message for moving a section + item across sections. + name (str): + Required. The resource name of the section item to move. + + Format: ``users/{user}/sections/{section}/items/{item}`` + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + target_section (str): + Required. The resource name of the section to move the + section item to. + + Format: ``users/{user}/sections/{section}`` + + This corresponds to the ``target_section`` 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.apps.chat_v1.types.MoveSectionItemResponse: + Response message for moving a section + item. + + """ + # Create or coerce a protobuf request 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, target_section] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, section.MoveSectionItemRequest): + request = section.MoveSectionItemRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + if target_section is not None: + request.target_section = target_section + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.move_section_item] + + # 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) -> "ChatServiceClient": return self diff --git a/packages/google-apps-chat/google/apps/chat_v1/services/chat_service/pagers.py b/packages/google-apps-chat/google/apps/chat_v1/services/chat_service/pagers.py index 2fa61873496a..ff5b2d48045d 100644 --- a/packages/google-apps-chat/google/apps/chat_v1/services/chat_service/pagers.py +++ b/packages/google-apps-chat/google/apps/chat_v1/services/chat_service/pagers.py @@ -38,7 +38,14 @@ OptionalRetry = Union[retries.Retry, object, None] # type: ignore OptionalAsyncRetry = Union[retries_async.AsyncRetry, object, None] # type: ignore -from google.apps.chat_v1.types import membership, message, reaction, space, space_event +from google.apps.chat_v1.types import ( + membership, + message, + reaction, + section, + space, + space_event, +) class ListMessagesPager: @@ -1131,3 +1138,315 @@ async def async_generator(): def __repr__(self) -> str: return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListSectionsPager: + """A pager for iterating through ``list_sections`` requests. + + This class thinly wraps an initial + :class:`google.apps.chat_v1.types.ListSectionsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``sections`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListSections`` requests and continue to iterate + through the ``sections`` field on the + corresponding responses. + + All the usual :class:`google.apps.chat_v1.types.ListSectionsResponse` + 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[..., section.ListSectionsResponse], + request: section.ListSectionsRequest, + response: section.ListSectionsResponse, + *, + 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.apps.chat_v1.types.ListSectionsRequest): + The initial request object. + response (google.apps.chat_v1.types.ListSectionsResponse): + 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 = section.ListSectionsRequest(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[section.ListSectionsResponse]: + 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[section.Section]: + for page in self.pages: + yield from page.sections + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListSectionsAsyncPager: + """A pager for iterating through ``list_sections`` requests. + + This class thinly wraps an initial + :class:`google.apps.chat_v1.types.ListSectionsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``sections`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListSections`` requests and continue to iterate + through the ``sections`` field on the + corresponding responses. + + All the usual :class:`google.apps.chat_v1.types.ListSectionsResponse` + 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[section.ListSectionsResponse]], + request: section.ListSectionsRequest, + response: section.ListSectionsResponse, + *, + 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.apps.chat_v1.types.ListSectionsRequest): + The initial request object. + response (google.apps.chat_v1.types.ListSectionsResponse): + 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 = section.ListSectionsRequest(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[section.ListSectionsResponse]: + 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[section.Section]: + async def async_generator(): + async for page in self.pages: + for response in page.sections: + yield response + + return async_generator() + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListSectionItemsPager: + """A pager for iterating through ``list_section_items`` requests. + + This class thinly wraps an initial + :class:`google.apps.chat_v1.types.ListSectionItemsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``section_items`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListSectionItems`` requests and continue to iterate + through the ``section_items`` field on the + corresponding responses. + + All the usual :class:`google.apps.chat_v1.types.ListSectionItemsResponse` + 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[..., section.ListSectionItemsResponse], + request: section.ListSectionItemsRequest, + response: section.ListSectionItemsResponse, + *, + 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.apps.chat_v1.types.ListSectionItemsRequest): + The initial request object. + response (google.apps.chat_v1.types.ListSectionItemsResponse): + 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 = section.ListSectionItemsRequest(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[section.ListSectionItemsResponse]: + 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[section.SectionItem]: + for page in self.pages: + yield from page.section_items + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListSectionItemsAsyncPager: + """A pager for iterating through ``list_section_items`` requests. + + This class thinly wraps an initial + :class:`google.apps.chat_v1.types.ListSectionItemsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``section_items`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListSectionItems`` requests and continue to iterate + through the ``section_items`` field on the + corresponding responses. + + All the usual :class:`google.apps.chat_v1.types.ListSectionItemsResponse` + 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[section.ListSectionItemsResponse]], + request: section.ListSectionItemsRequest, + response: section.ListSectionItemsResponse, + *, + 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.apps.chat_v1.types.ListSectionItemsRequest): + The initial request object. + response (google.apps.chat_v1.types.ListSectionItemsResponse): + 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 = section.ListSectionItemsRequest(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[section.ListSectionItemsResponse]: + 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[section.SectionItem]: + async def async_generator(): + async for page in self.pages: + for response in page.section_items: + yield response + + return async_generator() + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) diff --git a/packages/google-apps-chat/google/apps/chat_v1/services/chat_service/transports/base.py b/packages/google-apps-chat/google/apps/chat_v1/services/chat_service/transports/base.py index 124a8e57741f..1726e664dcaa 100644 --- a/packages/google-apps-chat/google/apps/chat_v1/services/chat_service/transports/base.py +++ b/packages/google-apps-chat/google/apps/chat_v1/services/chat_service/transports/base.py @@ -32,6 +32,7 @@ membership, message, reaction, + section, space, space_event, space_notification_setting, @@ -42,6 +43,7 @@ from google.apps.chat_v1.types import membership as gc_membership from google.apps.chat_v1.types import message as gc_message from google.apps.chat_v1.types import reaction as gc_reaction +from google.apps.chat_v1.types import section as gc_section from google.apps.chat_v1.types import space as gc_space from google.apps.chat_v1.types import ( space_notification_setting as gc_space_notification_setting, @@ -67,9 +69,11 @@ class ChatServiceTransport(abc.ABC): "https://www.googleapis.com/auth/chat.admin.spaces.readonly", "https://www.googleapis.com/auth/chat.app.delete", "https://www.googleapis.com/auth/chat.app.memberships", + "https://www.googleapis.com/auth/chat.app.memberships.readonly", "https://www.googleapis.com/auth/chat.app.messages.readonly", "https://www.googleapis.com/auth/chat.app.spaces", "https://www.googleapis.com/auth/chat.app.spaces.create", + "https://www.googleapis.com/auth/chat.app.spaces.readonly", "https://www.googleapis.com/auth/chat.bot", "https://www.googleapis.com/auth/chat.customemojis", "https://www.googleapis.com/auth/chat.customemojis.readonly", @@ -89,6 +93,8 @@ class ChatServiceTransport(abc.ABC): "https://www.googleapis.com/auth/chat.spaces.readonly", "https://www.googleapis.com/auth/chat.users.readstate", "https://www.googleapis.com/auth/chat.users.readstate.readonly", + "https://www.googleapis.com/auth/chat.users.sections", + "https://www.googleapis.com/auth/chat.users.sections.readonly", "https://www.googleapis.com/auth/chat.users.spacesettings", ) @@ -683,6 +689,104 @@ def _prep_wrapped_messages(self, client_info): default_timeout=30.0, client_info=client_info, ), + self.create_section: gapic_v1.method.wrap_method( + self.create_section, + default_retry=retries.Retry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=30.0, + ), + default_timeout=30.0, + client_info=client_info, + ), + self.delete_section: gapic_v1.method.wrap_method( + self.delete_section, + default_retry=retries.Retry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=30.0, + ), + default_timeout=30.0, + client_info=client_info, + ), + self.update_section: gapic_v1.method.wrap_method( + self.update_section, + default_retry=retries.Retry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=30.0, + ), + default_timeout=30.0, + client_info=client_info, + ), + self.list_sections: gapic_v1.method.wrap_method( + self.list_sections, + default_retry=retries.Retry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=30.0, + ), + default_timeout=30.0, + client_info=client_info, + ), + self.position_section: gapic_v1.method.wrap_method( + self.position_section, + default_retry=retries.Retry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=30.0, + ), + default_timeout=30.0, + client_info=client_info, + ), + self.list_section_items: gapic_v1.method.wrap_method( + self.list_section_items, + default_retry=retries.Retry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=30.0, + ), + default_timeout=30.0, + client_info=client_info, + ), + self.move_section_item: gapic_v1.method.wrap_method( + self.move_section_item, + default_retry=retries.Retry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=30.0, + ), + default_timeout=30.0, + client_info=client_info, + ), } def close(self): @@ -1031,6 +1135,76 @@ def update_space_notification_setting( ]: raise NotImplementedError() + @property + def create_section( + self, + ) -> Callable[ + [gc_section.CreateSectionRequest], + Union[gc_section.Section, Awaitable[gc_section.Section]], + ]: + raise NotImplementedError() + + @property + def delete_section( + self, + ) -> Callable[ + [section.DeleteSectionRequest], + Union[empty_pb2.Empty, Awaitable[empty_pb2.Empty]], + ]: + raise NotImplementedError() + + @property + def update_section( + self, + ) -> Callable[ + [gc_section.UpdateSectionRequest], + Union[gc_section.Section, Awaitable[gc_section.Section]], + ]: + raise NotImplementedError() + + @property + def list_sections( + self, + ) -> Callable[ + [section.ListSectionsRequest], + Union[section.ListSectionsResponse, Awaitable[section.ListSectionsResponse]], + ]: + raise NotImplementedError() + + @property + def position_section( + self, + ) -> Callable[ + [section.PositionSectionRequest], + Union[ + section.PositionSectionResponse, Awaitable[section.PositionSectionResponse] + ], + ]: + raise NotImplementedError() + + @property + def list_section_items( + self, + ) -> Callable[ + [section.ListSectionItemsRequest], + Union[ + section.ListSectionItemsResponse, + Awaitable[section.ListSectionItemsResponse], + ], + ]: + raise NotImplementedError() + + @property + def move_section_item( + self, + ) -> Callable[ + [section.MoveSectionItemRequest], + Union[ + section.MoveSectionItemResponse, Awaitable[section.MoveSectionItemResponse] + ], + ]: + raise NotImplementedError() + @property def kind(self) -> str: raise NotImplementedError() diff --git a/packages/google-apps-chat/google/apps/chat_v1/services/chat_service/transports/grpc.py b/packages/google-apps-chat/google/apps/chat_v1/services/chat_service/transports/grpc.py index f3d9eecdf896..a5ab6a47b320 100644 --- a/packages/google-apps-chat/google/apps/chat_v1/services/chat_service/transports/grpc.py +++ b/packages/google-apps-chat/google/apps/chat_v1/services/chat_service/transports/grpc.py @@ -34,6 +34,7 @@ membership, message, reaction, + section, space, space_event, space_notification_setting, @@ -44,6 +45,7 @@ from google.apps.chat_v1.types import membership as gc_membership from google.apps.chat_v1.types import message as gc_message from google.apps.chat_v1.types import reaction as gc_reaction +from google.apps.chat_v1.types import section as gc_section from google.apps.chat_v1.types import space as gc_space from google.apps.chat_v1.types import ( space_notification_setting as gc_space_notification_setting, @@ -444,9 +446,7 @@ def list_messages( - `App authentication `__ with `administrator - approval `__ in - `Developer - Preview `__ + approval `__ with the authorization scope: - ``https://www.googleapis.com/auth/chat.app.messages.readonly``. @@ -624,9 +624,7 @@ def get_message(self) -> Callable[[message.GetMessageRequest], message.Message]: that invoke the Chat app. - ``https://www.googleapis.com/auth/chat.app.messages.readonly`` with `administrator - approval `__ - (available in `Developer - Preview `__). + approval `__. When using this authentication scope, this method returns details about a public message in a space. @@ -1974,14 +1972,14 @@ def get_space_event( - `App authentication `__ with `administrator - approval `__ in - `Developer - Preview `__ + approval `__ with one of the following authorization scopes: - ``https://www.googleapis.com/auth/chat.app.spaces`` + - ``https://www.googleapis.com/auth/chat.app.spaces.readonly`` - ``https://www.googleapis.com/auth/chat.app.messages.readonly`` - ``https://www.googleapis.com/auth/chat.app.memberships`` + - ``https://www.googleapis.com/auth/chat.app.memberships.readonly`` - `User authentication `__ @@ -2047,14 +2045,14 @@ def list_space_events( - `App authentication `__ with `administrator - approval `__ in - `Developer - Preview `__ + approval `__ with one of the following authorization scopes: - ``https://www.googleapis.com/auth/chat.app.spaces`` + - ``https://www.googleapis.com/auth/chat.app.spaces.readonly`` - ``https://www.googleapis.com/auth/chat.app.messages.readonly`` - ``https://www.googleapis.com/auth/chat.app.memberships`` + - ``https://www.googleapis.com/auth/chat.app.memberships.readonly`` - `User authentication `__ @@ -2174,6 +2172,267 @@ def update_space_notification_setting( ) return self._stubs["update_space_notification_setting"] + @property + def create_section( + self, + ) -> Callable[[gc_section.CreateSectionRequest], gc_section.Section]: + r"""Return a callable for the create section method over gRPC. + + Creates a section in Google Chat. Sections help users group + conversations and customize the list of spaces displayed in Chat + navigation panel. Only sections of type ``CUSTOM_SECTION`` can + be created. For details, see `Create and organize sections in + Google + Chat `__. + + Requires `user + authentication `__ + with the `authorization + scope `__: + + - ``https://www.googleapis.com/auth/chat.users.sections`` + + Returns: + Callable[[~.CreateSectionRequest], + ~.Section]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_section" not in self._stubs: + self._stubs["create_section"] = self._logged_channel.unary_unary( + "/google.chat.v1.ChatService/CreateSection", + request_serializer=gc_section.CreateSectionRequest.serialize, + response_deserializer=gc_section.Section.deserialize, + ) + return self._stubs["create_section"] + + @property + def delete_section( + self, + ) -> Callable[[section.DeleteSectionRequest], empty_pb2.Empty]: + r"""Return a callable for the delete section method over gRPC. + + Deletes a section of type ``CUSTOM_SECTION``. + + If the section contains items, such as spaces, the items are + moved to Google Chat's default sections and are not deleted. + + For details, see `Create and organize sections in Google + Chat `__. + + Requires `user + authentication `__ + with the `authorization + scope `__: + + - ``https://www.googleapis.com/auth/chat.users.sections`` + + Returns: + Callable[[~.DeleteSectionRequest], + ~.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_section" not in self._stubs: + self._stubs["delete_section"] = self._logged_channel.unary_unary( + "/google.chat.v1.ChatService/DeleteSection", + request_serializer=section.DeleteSectionRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs["delete_section"] + + @property + def update_section( + self, + ) -> Callable[[gc_section.UpdateSectionRequest], gc_section.Section]: + r"""Return a callable for the update section method over gRPC. + + Updates a section. Only sections of type ``CUSTOM_SECTION`` can + be updated. For details, see `Create and organize sections in + Google + Chat `__. + + Requires `user + authentication `__ + with the `authorization + scope `__: + + - ``https://www.googleapis.com/auth/chat.users.sections`` + + Returns: + Callable[[~.UpdateSectionRequest], + ~.Section]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_section" not in self._stubs: + self._stubs["update_section"] = self._logged_channel.unary_unary( + "/google.chat.v1.ChatService/UpdateSection", + request_serializer=gc_section.UpdateSectionRequest.serialize, + response_deserializer=gc_section.Section.deserialize, + ) + return self._stubs["update_section"] + + @property + def list_sections( + self, + ) -> Callable[[section.ListSectionsRequest], section.ListSectionsResponse]: + r"""Return a callable for the list sections method over gRPC. + + Lists sections available to the Chat user. Sections help users + group their conversations and customize the list of spaces + displayed in Chat navigation panel. For details, see `Create and + organize sections in Google + Chat `__. + + Requires `user + authentication `__ + with the `authorization + scope `__: + + - ``https://www.googleapis.com/auth/chat.users.sections`` + - ``https://www.googleapis.com/auth/chat.users.sections.readonly`` + + Returns: + Callable[[~.ListSectionsRequest], + ~.ListSectionsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_sections" not in self._stubs: + self._stubs["list_sections"] = self._logged_channel.unary_unary( + "/google.chat.v1.ChatService/ListSections", + request_serializer=section.ListSectionsRequest.serialize, + response_deserializer=section.ListSectionsResponse.deserialize, + ) + return self._stubs["list_sections"] + + @property + def position_section( + self, + ) -> Callable[[section.PositionSectionRequest], section.PositionSectionResponse]: + r"""Return a callable for the position section method over gRPC. + + Changes the sort order of a section. For details, see `Create + and organize sections in Google + Chat `__. + + Requires `user + authentication `__ + with the `authorization + scope `__: + + - ``https://www.googleapis.com/auth/chat.users.sections`` + + Returns: + Callable[[~.PositionSectionRequest], + ~.PositionSectionResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "position_section" not in self._stubs: + self._stubs["position_section"] = self._logged_channel.unary_unary( + "/google.chat.v1.ChatService/PositionSection", + request_serializer=section.PositionSectionRequest.serialize, + response_deserializer=section.PositionSectionResponse.deserialize, + ) + return self._stubs["position_section"] + + @property + def list_section_items( + self, + ) -> Callable[[section.ListSectionItemsRequest], section.ListSectionItemsResponse]: + r"""Return a callable for the list section items method over gRPC. + + Lists items in a section. + + Only spaces can be section items. For details, see `Create and + organize sections in Google + Chat `__. + + Requires `user + authentication `__ + with the `authorization + scope `__: + + - ``https://www.googleapis.com/auth/chat.users.sections`` + - ``https://www.googleapis.com/auth/chat.users.sections.readonly`` + + Returns: + Callable[[~.ListSectionItemsRequest], + ~.ListSectionItemsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_section_items" not in self._stubs: + self._stubs["list_section_items"] = self._logged_channel.unary_unary( + "/google.chat.v1.ChatService/ListSectionItems", + request_serializer=section.ListSectionItemsRequest.serialize, + response_deserializer=section.ListSectionItemsResponse.deserialize, + ) + return self._stubs["list_section_items"] + + @property + def move_section_item( + self, + ) -> Callable[[section.MoveSectionItemRequest], section.MoveSectionItemResponse]: + r"""Return a callable for the move section item method over gRPC. + + Moves an item from one section to another. For example, if a + section contains spaces, this method can be used to move a space + to a different section. For details, see `Create and organize + sections in Google + Chat `__. + + Requires `user + authentication `__ + with the `authorization + scope `__: + + - ``https://www.googleapis.com/auth/chat.users.sections`` + + Returns: + Callable[[~.MoveSectionItemRequest], + ~.MoveSectionItemResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "move_section_item" not in self._stubs: + self._stubs["move_section_item"] = self._logged_channel.unary_unary( + "/google.chat.v1.ChatService/MoveSectionItem", + request_serializer=section.MoveSectionItemRequest.serialize, + response_deserializer=section.MoveSectionItemResponse.deserialize, + ) + return self._stubs["move_section_item"] + def close(self): self._logged_channel.close() diff --git a/packages/google-apps-chat/google/apps/chat_v1/services/chat_service/transports/grpc_asyncio.py b/packages/google-apps-chat/google/apps/chat_v1/services/chat_service/transports/grpc_asyncio.py index 1dde1db5c5f3..50fac72a710f 100644 --- a/packages/google-apps-chat/google/apps/chat_v1/services/chat_service/transports/grpc_asyncio.py +++ b/packages/google-apps-chat/google/apps/chat_v1/services/chat_service/transports/grpc_asyncio.py @@ -37,6 +37,7 @@ membership, message, reaction, + section, space, space_event, space_notification_setting, @@ -47,6 +48,7 @@ from google.apps.chat_v1.types import membership as gc_membership from google.apps.chat_v1.types import message as gc_message from google.apps.chat_v1.types import reaction as gc_reaction +from google.apps.chat_v1.types import section as gc_section from google.apps.chat_v1.types import space as gc_space from google.apps.chat_v1.types import ( space_notification_setting as gc_space_notification_setting, @@ -454,9 +456,7 @@ def list_messages( - `App authentication `__ with `administrator - approval `__ in - `Developer - Preview `__ + approval `__ with the authorization scope: - ``https://www.googleapis.com/auth/chat.app.messages.readonly``. @@ -637,9 +637,7 @@ def get_message( that invoke the Chat app. - ``https://www.googleapis.com/auth/chat.app.messages.readonly`` with `administrator - approval `__ - (available in `Developer - Preview `__). + approval `__. When using this authentication scope, this method returns details about a public message in a space. @@ -2008,14 +2006,14 @@ def get_space_event( - `App authentication `__ with `administrator - approval `__ in - `Developer - Preview `__ + approval `__ with one of the following authorization scopes: - ``https://www.googleapis.com/auth/chat.app.spaces`` + - ``https://www.googleapis.com/auth/chat.app.spaces.readonly`` - ``https://www.googleapis.com/auth/chat.app.messages.readonly`` - ``https://www.googleapis.com/auth/chat.app.memberships`` + - ``https://www.googleapis.com/auth/chat.app.memberships.readonly`` - `User authentication `__ @@ -2082,14 +2080,14 @@ def list_space_events( - `App authentication `__ with `administrator - approval `__ in - `Developer - Preview `__ + approval `__ with one of the following authorization scopes: - ``https://www.googleapis.com/auth/chat.app.spaces`` + - ``https://www.googleapis.com/auth/chat.app.spaces.readonly`` - ``https://www.googleapis.com/auth/chat.app.messages.readonly`` - ``https://www.googleapis.com/auth/chat.app.memberships`` + - ``https://www.googleapis.com/auth/chat.app.memberships.readonly`` - `User authentication `__ @@ -2209,6 +2207,275 @@ def update_space_notification_setting( ) return self._stubs["update_space_notification_setting"] + @property + def create_section( + self, + ) -> Callable[[gc_section.CreateSectionRequest], Awaitable[gc_section.Section]]: + r"""Return a callable for the create section method over gRPC. + + Creates a section in Google Chat. Sections help users group + conversations and customize the list of spaces displayed in Chat + navigation panel. Only sections of type ``CUSTOM_SECTION`` can + be created. For details, see `Create and organize sections in + Google + Chat `__. + + Requires `user + authentication `__ + with the `authorization + scope `__: + + - ``https://www.googleapis.com/auth/chat.users.sections`` + + Returns: + Callable[[~.CreateSectionRequest], + Awaitable[~.Section]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_section" not in self._stubs: + self._stubs["create_section"] = self._logged_channel.unary_unary( + "/google.chat.v1.ChatService/CreateSection", + request_serializer=gc_section.CreateSectionRequest.serialize, + response_deserializer=gc_section.Section.deserialize, + ) + return self._stubs["create_section"] + + @property + def delete_section( + self, + ) -> Callable[[section.DeleteSectionRequest], Awaitable[empty_pb2.Empty]]: + r"""Return a callable for the delete section method over gRPC. + + Deletes a section of type ``CUSTOM_SECTION``. + + If the section contains items, such as spaces, the items are + moved to Google Chat's default sections and are not deleted. + + For details, see `Create and organize sections in Google + Chat `__. + + Requires `user + authentication `__ + with the `authorization + scope `__: + + - ``https://www.googleapis.com/auth/chat.users.sections`` + + Returns: + Callable[[~.DeleteSectionRequest], + 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_section" not in self._stubs: + self._stubs["delete_section"] = self._logged_channel.unary_unary( + "/google.chat.v1.ChatService/DeleteSection", + request_serializer=section.DeleteSectionRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs["delete_section"] + + @property + def update_section( + self, + ) -> Callable[[gc_section.UpdateSectionRequest], Awaitable[gc_section.Section]]: + r"""Return a callable for the update section method over gRPC. + + Updates a section. Only sections of type ``CUSTOM_SECTION`` can + be updated. For details, see `Create and organize sections in + Google + Chat `__. + + Requires `user + authentication `__ + with the `authorization + scope `__: + + - ``https://www.googleapis.com/auth/chat.users.sections`` + + Returns: + Callable[[~.UpdateSectionRequest], + Awaitable[~.Section]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_section" not in self._stubs: + self._stubs["update_section"] = self._logged_channel.unary_unary( + "/google.chat.v1.ChatService/UpdateSection", + request_serializer=gc_section.UpdateSectionRequest.serialize, + response_deserializer=gc_section.Section.deserialize, + ) + return self._stubs["update_section"] + + @property + def list_sections( + self, + ) -> Callable[ + [section.ListSectionsRequest], Awaitable[section.ListSectionsResponse] + ]: + r"""Return a callable for the list sections method over gRPC. + + Lists sections available to the Chat user. Sections help users + group their conversations and customize the list of spaces + displayed in Chat navigation panel. For details, see `Create and + organize sections in Google + Chat `__. + + Requires `user + authentication `__ + with the `authorization + scope `__: + + - ``https://www.googleapis.com/auth/chat.users.sections`` + - ``https://www.googleapis.com/auth/chat.users.sections.readonly`` + + Returns: + Callable[[~.ListSectionsRequest], + Awaitable[~.ListSectionsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_sections" not in self._stubs: + self._stubs["list_sections"] = self._logged_channel.unary_unary( + "/google.chat.v1.ChatService/ListSections", + request_serializer=section.ListSectionsRequest.serialize, + response_deserializer=section.ListSectionsResponse.deserialize, + ) + return self._stubs["list_sections"] + + @property + def position_section( + self, + ) -> Callable[ + [section.PositionSectionRequest], Awaitable[section.PositionSectionResponse] + ]: + r"""Return a callable for the position section method over gRPC. + + Changes the sort order of a section. For details, see `Create + and organize sections in Google + Chat `__. + + Requires `user + authentication `__ + with the `authorization + scope `__: + + - ``https://www.googleapis.com/auth/chat.users.sections`` + + Returns: + Callable[[~.PositionSectionRequest], + Awaitable[~.PositionSectionResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "position_section" not in self._stubs: + self._stubs["position_section"] = self._logged_channel.unary_unary( + "/google.chat.v1.ChatService/PositionSection", + request_serializer=section.PositionSectionRequest.serialize, + response_deserializer=section.PositionSectionResponse.deserialize, + ) + return self._stubs["position_section"] + + @property + def list_section_items( + self, + ) -> Callable[ + [section.ListSectionItemsRequest], Awaitable[section.ListSectionItemsResponse] + ]: + r"""Return a callable for the list section items method over gRPC. + + Lists items in a section. + + Only spaces can be section items. For details, see `Create and + organize sections in Google + Chat `__. + + Requires `user + authentication `__ + with the `authorization + scope `__: + + - ``https://www.googleapis.com/auth/chat.users.sections`` + - ``https://www.googleapis.com/auth/chat.users.sections.readonly`` + + Returns: + Callable[[~.ListSectionItemsRequest], + Awaitable[~.ListSectionItemsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_section_items" not in self._stubs: + self._stubs["list_section_items"] = self._logged_channel.unary_unary( + "/google.chat.v1.ChatService/ListSectionItems", + request_serializer=section.ListSectionItemsRequest.serialize, + response_deserializer=section.ListSectionItemsResponse.deserialize, + ) + return self._stubs["list_section_items"] + + @property + def move_section_item( + self, + ) -> Callable[ + [section.MoveSectionItemRequest], Awaitable[section.MoveSectionItemResponse] + ]: + r"""Return a callable for the move section item method over gRPC. + + Moves an item from one section to another. For example, if a + section contains spaces, this method can be used to move a space + to a different section. For details, see `Create and organize + sections in Google + Chat `__. + + Requires `user + authentication `__ + with the `authorization + scope `__: + + - ``https://www.googleapis.com/auth/chat.users.sections`` + + Returns: + Callable[[~.MoveSectionItemRequest], + Awaitable[~.MoveSectionItemResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "move_section_item" not in self._stubs: + self._stubs["move_section_item"] = self._logged_channel.unary_unary( + "/google.chat.v1.ChatService/MoveSectionItem", + request_serializer=section.MoveSectionItemRequest.serialize, + response_deserializer=section.MoveSectionItemResponse.deserialize, + ) + return self._stubs["move_section_item"] + def _prep_wrapped_messages(self, client_info): """Precompute the wrapped methods, overriding the base class method to use async wrappers.""" self._wrapped_methods = { @@ -2702,6 +2969,104 @@ def _prep_wrapped_messages(self, client_info): default_timeout=30.0, client_info=client_info, ), + self.create_section: self._wrap_method( + self.create_section, + default_retry=retries.AsyncRetry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=30.0, + ), + default_timeout=30.0, + client_info=client_info, + ), + self.delete_section: self._wrap_method( + self.delete_section, + default_retry=retries.AsyncRetry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=30.0, + ), + default_timeout=30.0, + client_info=client_info, + ), + self.update_section: self._wrap_method( + self.update_section, + default_retry=retries.AsyncRetry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=30.0, + ), + default_timeout=30.0, + client_info=client_info, + ), + self.list_sections: self._wrap_method( + self.list_sections, + default_retry=retries.AsyncRetry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=30.0, + ), + default_timeout=30.0, + client_info=client_info, + ), + self.position_section: self._wrap_method( + self.position_section, + default_retry=retries.AsyncRetry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=30.0, + ), + default_timeout=30.0, + client_info=client_info, + ), + self.list_section_items: self._wrap_method( + self.list_section_items, + default_retry=retries.AsyncRetry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=30.0, + ), + default_timeout=30.0, + client_info=client_info, + ), + self.move_section_item: self._wrap_method( + self.move_section_item, + default_retry=retries.AsyncRetry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=30.0, + ), + default_timeout=30.0, + client_info=client_info, + ), } def _wrap_method(self, func, *args, **kwargs): diff --git a/packages/google-apps-chat/google/apps/chat_v1/services/chat_service/transports/rest.py b/packages/google-apps-chat/google/apps/chat_v1/services/chat_service/transports/rest.py index a0b5a6ea4756..a8cd7e10e435 100644 --- a/packages/google-apps-chat/google/apps/chat_v1/services/chat_service/transports/rest.py +++ b/packages/google-apps-chat/google/apps/chat_v1/services/chat_service/transports/rest.py @@ -34,6 +34,7 @@ membership, message, reaction, + section, space, space_event, space_notification_setting, @@ -44,6 +45,7 @@ from google.apps.chat_v1.types import membership as gc_membership from google.apps.chat_v1.types import message as gc_message from google.apps.chat_v1.types import reaction as gc_reaction +from google.apps.chat_v1.types import section as gc_section from google.apps.chat_v1.types import space as gc_space from google.apps.chat_v1.types import ( space_notification_setting as gc_space_notification_setting, @@ -132,6 +134,14 @@ def post_create_reaction(self, response): logging.log(f"Received response: {response}") return response + def pre_create_section(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_section(self, response): + logging.log(f"Received response: {response}") + return response + def pre_create_space(self, request, metadata): logging.log(f"Received request: {request}") return request, metadata @@ -160,6 +170,10 @@ def pre_delete_reaction(self, request, metadata): logging.log(f"Received request: {request}") return request, metadata + def pre_delete_section(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + def pre_delete_space(self, request, metadata): logging.log(f"Received request: {request}") return request, metadata @@ -276,6 +290,22 @@ def post_list_reactions(self, response): logging.log(f"Received response: {response}") return response + def pre_list_section_items(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_section_items(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_sections(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_sections(self, response): + logging.log(f"Received response: {response}") + return response + def pre_list_space_events(self, request, metadata): logging.log(f"Received request: {request}") return request, metadata @@ -292,6 +322,22 @@ def post_list_spaces(self, response): logging.log(f"Received response: {response}") return response + def pre_move_section_item(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_move_section_item(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_position_section(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_position_section(self, response): + logging.log(f"Received response: {response}") + return response + def pre_search_spaces(self, request, metadata): logging.log(f"Received request: {request}") return request, metadata @@ -324,6 +370,14 @@ def post_update_message(self, response): logging.log(f"Received response: {response}") return response + def pre_update_section(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_section(self, response): + logging.log(f"Received response: {response}") + return response + def pre_update_space(self, request, metadata): logging.log(f"Received request: {request}") return request, metadata @@ -602,6 +656,52 @@ def post_create_reaction_with_metadata( """ return response, metadata + def pre_create_section( + self, + request: gc_section.CreateSectionRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + gc_section.CreateSectionRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for create_section + + Override in a subclass to manipulate the request or metadata + before they are sent to the ChatService server. + """ + return request, metadata + + def post_create_section(self, response: gc_section.Section) -> gc_section.Section: + """Post-rpc interceptor for create_section + + DEPRECATED. Please use the `post_create_section_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the ChatService server but before + it is returned to user code. This `post_create_section` interceptor runs + before the `post_create_section_with_metadata` interceptor. + """ + return response + + def post_create_section_with_metadata( + self, + response: gc_section.Section, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[gc_section.Section, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for create_section + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the ChatService server but before it is returned to user code. + + We recommend only using this `post_create_section_with_metadata` + interceptor in new development instead of the `post_create_section` interceptor. + When both interceptors are used, this `post_create_section_with_metadata` interceptor runs after the + `post_create_section` interceptor. The (possibly modified) response returned by + `post_create_section` will be passed to + `post_create_section_with_metadata`. + """ + return response, metadata + def pre_create_space( self, request: gc_space.CreateSpaceRequest, @@ -732,6 +832,18 @@ def pre_delete_reaction( """ return request, metadata + def pre_delete_section( + self, + request: section.DeleteSectionRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[section.DeleteSectionRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for delete_section + + Override in a subclass to manipulate the request or metadata + before they are sent to the ChatService server. + """ + return request, metadata + def pre_delete_space( self, request: space.DeleteSpaceRequest, @@ -1408,6 +1520,102 @@ def post_list_reactions_with_metadata( """ return response, metadata + def pre_list_section_items( + self, + request: section.ListSectionItemsRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + section.ListSectionItemsRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for list_section_items + + Override in a subclass to manipulate the request or metadata + before they are sent to the ChatService server. + """ + return request, metadata + + def post_list_section_items( + self, response: section.ListSectionItemsResponse + ) -> section.ListSectionItemsResponse: + """Post-rpc interceptor for list_section_items + + DEPRECATED. Please use the `post_list_section_items_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the ChatService server but before + it is returned to user code. This `post_list_section_items` interceptor runs + before the `post_list_section_items_with_metadata` interceptor. + """ + return response + + def post_list_section_items_with_metadata( + self, + response: section.ListSectionItemsResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + section.ListSectionItemsResponse, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Post-rpc interceptor for list_section_items + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the ChatService server but before it is returned to user code. + + We recommend only using this `post_list_section_items_with_metadata` + interceptor in new development instead of the `post_list_section_items` interceptor. + When both interceptors are used, this `post_list_section_items_with_metadata` interceptor runs after the + `post_list_section_items` interceptor. The (possibly modified) response returned by + `post_list_section_items` will be passed to + `post_list_section_items_with_metadata`. + """ + return response, metadata + + def pre_list_sections( + self, + request: section.ListSectionsRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[section.ListSectionsRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for list_sections + + Override in a subclass to manipulate the request or metadata + before they are sent to the ChatService server. + """ + return request, metadata + + def post_list_sections( + self, response: section.ListSectionsResponse + ) -> section.ListSectionsResponse: + """Post-rpc interceptor for list_sections + + DEPRECATED. Please use the `post_list_sections_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the ChatService server but before + it is returned to user code. This `post_list_sections` interceptor runs + before the `post_list_sections_with_metadata` interceptor. + """ + return response + + def post_list_sections_with_metadata( + self, + response: section.ListSectionsResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[section.ListSectionsResponse, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for list_sections + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the ChatService server but before it is returned to user code. + + We recommend only using this `post_list_sections_with_metadata` + interceptor in new development instead of the `post_list_sections` interceptor. + When both interceptors are used, this `post_list_sections_with_metadata` interceptor runs after the + `post_list_sections` interceptor. The (possibly modified) response returned by + `post_list_sections` will be passed to + `post_list_sections_with_metadata`. + """ + return response, metadata + def pre_list_space_events( self, request: space_event.ListSpaceEventsRequest, @@ -1504,6 +1712,102 @@ def post_list_spaces_with_metadata( """ return response, metadata + def pre_move_section_item( + self, + request: section.MoveSectionItemRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[section.MoveSectionItemRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for move_section_item + + Override in a subclass to manipulate the request or metadata + before they are sent to the ChatService server. + """ + return request, metadata + + def post_move_section_item( + self, response: section.MoveSectionItemResponse + ) -> section.MoveSectionItemResponse: + """Post-rpc interceptor for move_section_item + + DEPRECATED. Please use the `post_move_section_item_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the ChatService server but before + it is returned to user code. This `post_move_section_item` interceptor runs + before the `post_move_section_item_with_metadata` interceptor. + """ + return response + + def post_move_section_item_with_metadata( + self, + response: section.MoveSectionItemResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + section.MoveSectionItemResponse, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Post-rpc interceptor for move_section_item + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the ChatService server but before it is returned to user code. + + We recommend only using this `post_move_section_item_with_metadata` + interceptor in new development instead of the `post_move_section_item` interceptor. + When both interceptors are used, this `post_move_section_item_with_metadata` interceptor runs after the + `post_move_section_item` interceptor. The (possibly modified) response returned by + `post_move_section_item` will be passed to + `post_move_section_item_with_metadata`. + """ + return response, metadata + + def pre_position_section( + self, + request: section.PositionSectionRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[section.PositionSectionRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for position_section + + Override in a subclass to manipulate the request or metadata + before they are sent to the ChatService server. + """ + return request, metadata + + def post_position_section( + self, response: section.PositionSectionResponse + ) -> section.PositionSectionResponse: + """Post-rpc interceptor for position_section + + DEPRECATED. Please use the `post_position_section_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the ChatService server but before + it is returned to user code. This `post_position_section` interceptor runs + before the `post_position_section_with_metadata` interceptor. + """ + return response + + def post_position_section_with_metadata( + self, + response: section.PositionSectionResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + section.PositionSectionResponse, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Post-rpc interceptor for position_section + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the ChatService server but before it is returned to user code. + + We recommend only using this `post_position_section_with_metadata` + interceptor in new development instead of the `post_position_section` interceptor. + When both interceptors are used, this `post_position_section_with_metadata` interceptor runs after the + `post_position_section` interceptor. The (possibly modified) response returned by + `post_position_section` will be passed to + `post_position_section_with_metadata`. + """ + return response, metadata + def pre_search_spaces( self, request: space.SearchSpacesRequest, @@ -1686,6 +1990,52 @@ def post_update_message_with_metadata( """ return response, metadata + def pre_update_section( + self, + request: gc_section.UpdateSectionRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + gc_section.UpdateSectionRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for update_section + + Override in a subclass to manipulate the request or metadata + before they are sent to the ChatService server. + """ + return request, metadata + + def post_update_section(self, response: gc_section.Section) -> gc_section.Section: + """Post-rpc interceptor for update_section + + DEPRECATED. Please use the `post_update_section_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the ChatService server but before + it is returned to user code. This `post_update_section` interceptor runs + before the `post_update_section_with_metadata` interceptor. + """ + return response + + def post_update_section_with_metadata( + self, + response: gc_section.Section, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[gc_section.Section, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for update_section + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the ChatService server but before it is returned to user code. + + We recommend only using this `post_update_section_with_metadata` + interceptor in new development instead of the `post_update_section` interceptor. + When both interceptors are used, this `post_update_section_with_metadata` interceptor runs after the + `post_update_section` interceptor. The (possibly modified) response returned by + `post_update_section` will be passed to + `post_update_section_with_metadata`. + """ + return response, metadata + def pre_update_space( self, request: gc_space.UpdateSpaceRequest, @@ -2748,11 +3098,11 @@ def __call__( ) return resp - class _CreateSpace( - _BaseChatServiceRestTransport._BaseCreateSpace, ChatServiceRestStub + class _CreateSection( + _BaseChatServiceRestTransport._BaseCreateSection, ChatServiceRestStub ): def __hash__(self): - return hash("ChatServiceRestTransport.CreateSpace") + return hash("ChatServiceRestTransport.CreateSection") @staticmethod def _get_response( @@ -2779,18 +3129,18 @@ def _get_response( def __call__( self, - request: gc_space.CreateSpaceRequest, + request: gc_section.CreateSectionRequest, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> gc_space.Space: - r"""Call the create space method over HTTP. + ) -> gc_section.Section: + r"""Call the create section method over HTTP. Args: - request (~.gc_space.CreateSpaceRequest): - The request object. A request to create a named space - with no members. + request (~.gc_section.CreateSectionRequest): + The request object. Request message for creating a + section. retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -2800,34 +3150,48 @@ def __call__( be of type `bytes`. Returns: - ~.gc_space.Space: - A space in Google Chat. Spaces are - conversations between two or more users - or 1:1 messages between a user and a - Chat app. + ~.gc_section.Section: + Represents a + `section `__ + in Google Chat. Sections help users organize their + spaces. There are two types of sections: + + 1. **System Sections:** These are predefined sections + managed by Google Chat. Their resource names are + fixed, and they cannot be created, deleted, or have + their ``display_name`` modified. Examples include: + + - ``users/{user}/sections/default-direct-messages`` + - ``users/{user}/sections/default-spaces`` + - ``users/{user}/sections/default-apps`` + + 2. **Custom Sections:** These are sections created and + managed by the user. Creating a custom section using + ``CreateSection`` **requires** a ``display_name``. + Custom sections can be updated using + ``UpdateSection`` and deleted using + ``DeleteSection``. """ http_options = ( - _BaseChatServiceRestTransport._BaseCreateSpace._get_http_options() + _BaseChatServiceRestTransport._BaseCreateSection._get_http_options() ) - request, metadata = self._interceptor.pre_create_space(request, metadata) - transcoded_request = ( - _BaseChatServiceRestTransport._BaseCreateSpace._get_transcoded_request( - http_options, request - ) + request, metadata = self._interceptor.pre_create_section(request, metadata) + transcoded_request = _BaseChatServiceRestTransport._BaseCreateSection._get_transcoded_request( + http_options, request ) body = ( - _BaseChatServiceRestTransport._BaseCreateSpace._get_request_body_json( + _BaseChatServiceRestTransport._BaseCreateSection._get_request_body_json( transcoded_request ) ) # Jsonify the query params query_params = ( - _BaseChatServiceRestTransport._BaseCreateSpace._get_query_params_json( + _BaseChatServiceRestTransport._BaseCreateSection._get_query_params_json( transcoded_request ) ) @@ -2850,17 +3214,17 @@ def __call__( "headers": dict(metadata), } _LOGGER.debug( - f"Sending request for google.chat_v1.ChatServiceClient.CreateSpace", + f"Sending request for google.chat_v1.ChatServiceClient.CreateSection", extra={ "serviceName": "google.chat.v1.ChatService", - "rpcName": "CreateSpace", + "rpcName": "CreateSection", "httpRequest": http_request, "metadata": http_request["headers"], }, ) # Send the request - response = ChatServiceRestTransport._CreateSpace._get_response( + response = ChatServiceRestTransport._CreateSection._get_response( self._host, metadata, query_params, @@ -2876,21 +3240,21 @@ def __call__( raise core_exceptions.from_http_response(response) # Return the response - resp = gc_space.Space() - pb_resp = gc_space.Space.pb(resp) + resp = gc_section.Section() + pb_resp = gc_section.Section.pb(resp) json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_create_space(resp) + resp = self._interceptor.post_create_section(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_create_space_with_metadata( + resp, _ = self._interceptor.post_create_section_with_metadata( resp, response_metadata ) if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( logging.DEBUG ): # pragma: NO COVER try: - response_payload = gc_space.Space.to_json(response) + response_payload = gc_section.Section.to_json(response) except: response_payload = None http_response = { @@ -2899,21 +3263,21 @@ def __call__( "status": response.status_code, } _LOGGER.debug( - "Received response for google.chat_v1.ChatServiceClient.create_space", + "Received response for google.chat_v1.ChatServiceClient.create_section", extra={ "serviceName": "google.chat.v1.ChatService", - "rpcName": "CreateSpace", + "rpcName": "CreateSection", "metadata": http_response["headers"], "httpResponse": http_response, }, ) return resp - class _DeleteCustomEmoji( - _BaseChatServiceRestTransport._BaseDeleteCustomEmoji, ChatServiceRestStub + class _CreateSpace( + _BaseChatServiceRestTransport._BaseCreateSpace, ChatServiceRestStub ): def __hash__(self): - return hash("ChatServiceRestTransport.DeleteCustomEmoji") + return hash("ChatServiceRestTransport.CreateSpace") @staticmethod def _get_response( @@ -2934,18 +3298,179 @@ 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: reaction.DeleteCustomEmojiRequest, + request: gc_space.CreateSpaceRequest, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ): - r"""Call the delete custom emoji method over HTTP. + ) -> gc_space.Space: + r"""Call the create space method over HTTP. + + Args: + request (~.gc_space.CreateSpaceRequest): + The request object. A request to create a named space + with no members. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.gc_space.Space: + A space in Google Chat. Spaces are + conversations between two or more users + or 1:1 messages between a user and a + Chat app. + + """ + + http_options = ( + _BaseChatServiceRestTransport._BaseCreateSpace._get_http_options() + ) + + request, metadata = self._interceptor.pre_create_space(request, metadata) + transcoded_request = ( + _BaseChatServiceRestTransport._BaseCreateSpace._get_transcoded_request( + http_options, request + ) + ) + + body = ( + _BaseChatServiceRestTransport._BaseCreateSpace._get_request_body_json( + transcoded_request + ) + ) + + # Jsonify the query params + query_params = ( + _BaseChatServiceRestTransport._BaseCreateSpace._get_query_params_json( + transcoded_request + ) + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.chat_v1.ChatServiceClient.CreateSpace", + extra={ + "serviceName": "google.chat.v1.ChatService", + "rpcName": "CreateSpace", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = ChatServiceRestTransport._CreateSpace._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 = gc_space.Space() + pb_resp = gc_space.Space.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_create_space(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_create_space_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = gc_space.Space.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.chat_v1.ChatServiceClient.create_space", + extra={ + "serviceName": "google.chat.v1.ChatService", + "rpcName": "CreateSpace", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _DeleteCustomEmoji( + _BaseChatServiceRestTransport._BaseDeleteCustomEmoji, ChatServiceRestStub + ): + def __hash__(self): + return hash("ChatServiceRestTransport.DeleteCustomEmoji") + + @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: reaction.DeleteCustomEmojiRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ): + r"""Call the delete custom emoji method over HTTP. Args: request (~.reaction.DeleteCustomEmojiRequest): @@ -3382,6 +3907,115 @@ def __call__( if response.status_code >= 400: raise core_exceptions.from_http_response(response) + class _DeleteSection( + _BaseChatServiceRestTransport._BaseDeleteSection, ChatServiceRestStub + ): + def __hash__(self): + return hash("ChatServiceRestTransport.DeleteSection") + + @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: section.DeleteSectionRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ): + r"""Call the delete section method over HTTP. + + Args: + request (~.section.DeleteSectionRequest): + The request object. Request message for deleting a section. `Developer + Preview `__. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, 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 = ( + _BaseChatServiceRestTransport._BaseDeleteSection._get_http_options() + ) + + request, metadata = self._interceptor.pre_delete_section(request, metadata) + transcoded_request = _BaseChatServiceRestTransport._BaseDeleteSection._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = ( + _BaseChatServiceRestTransport._BaseDeleteSection._get_query_params_json( + transcoded_request + ) + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.chat_v1.ChatServiceClient.DeleteSection", + extra={ + "serviceName": "google.chat.v1.ChatService", + "rpcName": "DeleteSection", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = ChatServiceRestTransport._DeleteSection._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 _DeleteSpace( _BaseChatServiceRestTransport._BaseDeleteSpace, ChatServiceRestStub ): @@ -5594,8 +6228,309 @@ def __call__( ) return resp - class _ListSpaceEvents( - _BaseChatServiceRestTransport._BaseListSpaceEvents, ChatServiceRestStub + class _ListSectionItems( + _BaseChatServiceRestTransport._BaseListSectionItems, ChatServiceRestStub + ): + def __hash__(self): + return hash("ChatServiceRestTransport.ListSectionItems") + + @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: section.ListSectionItemsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> section.ListSectionItemsResponse: + r"""Call the list section items method over HTTP. + + Args: + request (~.section.ListSectionItemsRequest): + The request object. Request message for listing section + items. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.section.ListSectionItemsResponse: + Response message for listing section + items. + + """ + + http_options = ( + _BaseChatServiceRestTransport._BaseListSectionItems._get_http_options() + ) + + request, metadata = self._interceptor.pre_list_section_items( + request, metadata + ) + transcoded_request = _BaseChatServiceRestTransport._BaseListSectionItems._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = _BaseChatServiceRestTransport._BaseListSectionItems._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.chat_v1.ChatServiceClient.ListSectionItems", + extra={ + "serviceName": "google.chat.v1.ChatService", + "rpcName": "ListSectionItems", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = ChatServiceRestTransport._ListSectionItems._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 = section.ListSectionItemsResponse() + pb_resp = section.ListSectionItemsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_list_section_items(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_list_section_items_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = section.ListSectionItemsResponse.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.chat_v1.ChatServiceClient.list_section_items", + extra={ + "serviceName": "google.chat.v1.ChatService", + "rpcName": "ListSectionItems", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _ListSections( + _BaseChatServiceRestTransport._BaseListSections, ChatServiceRestStub + ): + def __hash__(self): + return hash("ChatServiceRestTransport.ListSections") + + @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: section.ListSectionsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> section.ListSectionsResponse: + r"""Call the list sections method over HTTP. + + Args: + request (~.section.ListSectionsRequest): + The request object. Request message for listing sections. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.section.ListSectionsResponse: + Response message for listing + sections. + + """ + + http_options = ( + _BaseChatServiceRestTransport._BaseListSections._get_http_options() + ) + + request, metadata = self._interceptor.pre_list_sections(request, metadata) + transcoded_request = ( + _BaseChatServiceRestTransport._BaseListSections._get_transcoded_request( + http_options, request + ) + ) + + # Jsonify the query params + query_params = ( + _BaseChatServiceRestTransport._BaseListSections._get_query_params_json( + transcoded_request + ) + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.chat_v1.ChatServiceClient.ListSections", + extra={ + "serviceName": "google.chat.v1.ChatService", + "rpcName": "ListSections", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = ChatServiceRestTransport._ListSections._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 = section.ListSectionsResponse() + pb_resp = section.ListSectionsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_list_sections(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_list_sections_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = section.ListSectionsResponse.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.chat_v1.ChatServiceClient.list_sections", + extra={ + "serviceName": "google.chat.v1.ChatService", + "rpcName": "ListSections", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _ListSpaceEvents( + _BaseChatServiceRestTransport._BaseListSpaceEvents, ChatServiceRestStub ): def __hash__(self): return hash("ChatServiceRestTransport.ListSpaceEvents") @@ -5624,18 +6559,321 @@ def _get_response( def __call__( self, - request: space_event.ListSpaceEventsRequest, + request: space_event.ListSpaceEventsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> space_event.ListSpaceEventsResponse: + r"""Call the list space events method over HTTP. + + Args: + request (~.space_event.ListSpaceEventsRequest): + The request object. Request message for listing space + events. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.space_event.ListSpaceEventsResponse: + Response message for listing space + events. + + """ + + http_options = ( + _BaseChatServiceRestTransport._BaseListSpaceEvents._get_http_options() + ) + + request, metadata = self._interceptor.pre_list_space_events( + request, metadata + ) + transcoded_request = _BaseChatServiceRestTransport._BaseListSpaceEvents._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = _BaseChatServiceRestTransport._BaseListSpaceEvents._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.chat_v1.ChatServiceClient.ListSpaceEvents", + extra={ + "serviceName": "google.chat.v1.ChatService", + "rpcName": "ListSpaceEvents", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = ChatServiceRestTransport._ListSpaceEvents._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 = space_event.ListSpaceEventsResponse() + pb_resp = space_event.ListSpaceEventsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_list_space_events(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_list_space_events_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = space_event.ListSpaceEventsResponse.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.chat_v1.ChatServiceClient.list_space_events", + extra={ + "serviceName": "google.chat.v1.ChatService", + "rpcName": "ListSpaceEvents", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _ListSpaces( + _BaseChatServiceRestTransport._BaseListSpaces, ChatServiceRestStub + ): + def __hash__(self): + return hash("ChatServiceRestTransport.ListSpaces") + + @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: space.ListSpacesRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> space.ListSpacesResponse: + r"""Call the list spaces method over HTTP. + + Args: + request (~.space.ListSpacesRequest): + The request object. A request to list the spaces the + caller is a member of. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.space.ListSpacesResponse: + The response for a list spaces + request. + + """ + + http_options = ( + _BaseChatServiceRestTransport._BaseListSpaces._get_http_options() + ) + + request, metadata = self._interceptor.pre_list_spaces(request, metadata) + transcoded_request = ( + _BaseChatServiceRestTransport._BaseListSpaces._get_transcoded_request( + http_options, request + ) + ) + + # Jsonify the query params + query_params = ( + _BaseChatServiceRestTransport._BaseListSpaces._get_query_params_json( + transcoded_request + ) + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.chat_v1.ChatServiceClient.ListSpaces", + extra={ + "serviceName": "google.chat.v1.ChatService", + "rpcName": "ListSpaces", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = ChatServiceRestTransport._ListSpaces._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 = space.ListSpacesResponse() + pb_resp = space.ListSpacesResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_list_spaces(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_list_spaces_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = space.ListSpacesResponse.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.chat_v1.ChatServiceClient.list_spaces", + extra={ + "serviceName": "google.chat.v1.ChatService", + "rpcName": "ListSpaces", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _MoveSectionItem( + _BaseChatServiceRestTransport._BaseMoveSectionItem, ChatServiceRestStub + ): + def __hash__(self): + return hash("ChatServiceRestTransport.MoveSectionItem") + + @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: section.MoveSectionItemRequest, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> space_event.ListSpaceEventsResponse: - r"""Call the list space events method over HTTP. + ) -> section.MoveSectionItemResponse: + r"""Call the move section item method over HTTP. Args: - request (~.space_event.ListSpaceEventsRequest): - The request object. Request message for listing space - events. + request (~.section.MoveSectionItemRequest): + The request object. Request message for moving a section + item across sections. retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -5645,25 +6883,29 @@ def __call__( be of type `bytes`. Returns: - ~.space_event.ListSpaceEventsResponse: - Response message for listing space - events. + ~.section.MoveSectionItemResponse: + Response message for moving a section + item. """ http_options = ( - _BaseChatServiceRestTransport._BaseListSpaceEvents._get_http_options() + _BaseChatServiceRestTransport._BaseMoveSectionItem._get_http_options() ) - request, metadata = self._interceptor.pre_list_space_events( + request, metadata = self._interceptor.pre_move_section_item( request, metadata ) - transcoded_request = _BaseChatServiceRestTransport._BaseListSpaceEvents._get_transcoded_request( + transcoded_request = _BaseChatServiceRestTransport._BaseMoveSectionItem._get_transcoded_request( http_options, request ) + body = _BaseChatServiceRestTransport._BaseMoveSectionItem._get_request_body_json( + transcoded_request + ) + # Jsonify the query params - query_params = _BaseChatServiceRestTransport._BaseListSpaceEvents._get_query_params_json( + query_params = _BaseChatServiceRestTransport._BaseMoveSectionItem._get_query_params_json( transcoded_request ) @@ -5685,23 +6927,24 @@ def __call__( "headers": dict(metadata), } _LOGGER.debug( - f"Sending request for google.chat_v1.ChatServiceClient.ListSpaceEvents", + f"Sending request for google.chat_v1.ChatServiceClient.MoveSectionItem", extra={ "serviceName": "google.chat.v1.ChatService", - "rpcName": "ListSpaceEvents", + "rpcName": "MoveSectionItem", "httpRequest": http_request, "metadata": http_request["headers"], }, ) # Send the request - response = ChatServiceRestTransport._ListSpaceEvents._get_response( + response = ChatServiceRestTransport._MoveSectionItem._get_response( self._host, metadata, query_params, self._session, timeout, transcoded_request, + body, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -5710,23 +6953,21 @@ def __call__( raise core_exceptions.from_http_response(response) # Return the response - resp = space_event.ListSpaceEventsResponse() - pb_resp = space_event.ListSpaceEventsResponse.pb(resp) + resp = section.MoveSectionItemResponse() + pb_resp = section.MoveSectionItemResponse.pb(resp) json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_list_space_events(resp) + resp = self._interceptor.post_move_section_item(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_list_space_events_with_metadata( + resp, _ = self._interceptor.post_move_section_item_with_metadata( resp, response_metadata ) if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( logging.DEBUG ): # pragma: NO COVER try: - response_payload = space_event.ListSpaceEventsResponse.to_json( - response - ) + response_payload = section.MoveSectionItemResponse.to_json(response) except: response_payload = None http_response = { @@ -5735,21 +6976,21 @@ def __call__( "status": response.status_code, } _LOGGER.debug( - "Received response for google.chat_v1.ChatServiceClient.list_space_events", + "Received response for google.chat_v1.ChatServiceClient.move_section_item", extra={ "serviceName": "google.chat.v1.ChatService", - "rpcName": "ListSpaceEvents", + "rpcName": "MoveSectionItem", "metadata": http_response["headers"], "httpResponse": http_response, }, ) return resp - class _ListSpaces( - _BaseChatServiceRestTransport._BaseListSpaces, ChatServiceRestStub + class _PositionSection( + _BaseChatServiceRestTransport._BasePositionSection, ChatServiceRestStub ): def __hash__(self): - return hash("ChatServiceRestTransport.ListSpaces") + return hash("ChatServiceRestTransport.PositionSection") @staticmethod def _get_response( @@ -5770,23 +7011,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: space.ListSpacesRequest, + request: section.PositionSectionRequest, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> space.ListSpacesResponse: - r"""Call the list spaces method over HTTP. + ) -> section.PositionSectionResponse: + r"""Call the position section method over HTTP. Args: - request (~.space.ListSpacesRequest): - The request object. A request to list the spaces the - caller is a member of. + request (~.section.PositionSectionRequest): + The request object. Request message for positioning a + section. retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -5796,28 +7038,30 @@ def __call__( be of type `bytes`. Returns: - ~.space.ListSpacesResponse: - The response for a list spaces - request. + ~.section.PositionSectionResponse: + Response message for positioning a + section. """ http_options = ( - _BaseChatServiceRestTransport._BaseListSpaces._get_http_options() + _BaseChatServiceRestTransport._BasePositionSection._get_http_options() ) - request, metadata = self._interceptor.pre_list_spaces(request, metadata) - transcoded_request = ( - _BaseChatServiceRestTransport._BaseListSpaces._get_transcoded_request( - http_options, request - ) + request, metadata = self._interceptor.pre_position_section( + request, metadata + ) + transcoded_request = _BaseChatServiceRestTransport._BasePositionSection._get_transcoded_request( + http_options, request + ) + + body = _BaseChatServiceRestTransport._BasePositionSection._get_request_body_json( + transcoded_request ) # Jsonify the query params - query_params = ( - _BaseChatServiceRestTransport._BaseListSpaces._get_query_params_json( - transcoded_request - ) + query_params = _BaseChatServiceRestTransport._BasePositionSection._get_query_params_json( + transcoded_request ) if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( @@ -5838,23 +7082,24 @@ def __call__( "headers": dict(metadata), } _LOGGER.debug( - f"Sending request for google.chat_v1.ChatServiceClient.ListSpaces", + f"Sending request for google.chat_v1.ChatServiceClient.PositionSection", extra={ "serviceName": "google.chat.v1.ChatService", - "rpcName": "ListSpaces", + "rpcName": "PositionSection", "httpRequest": http_request, "metadata": http_request["headers"], }, ) # Send the request - response = ChatServiceRestTransport._ListSpaces._get_response( + response = ChatServiceRestTransport._PositionSection._get_response( self._host, metadata, query_params, self._session, timeout, transcoded_request, + body, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -5863,21 +7108,21 @@ def __call__( raise core_exceptions.from_http_response(response) # Return the response - resp = space.ListSpacesResponse() - pb_resp = space.ListSpacesResponse.pb(resp) + resp = section.PositionSectionResponse() + pb_resp = section.PositionSectionResponse.pb(resp) json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_list_spaces(resp) + resp = self._interceptor.post_position_section(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_list_spaces_with_metadata( + resp, _ = self._interceptor.post_position_section_with_metadata( resp, response_metadata ) if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( logging.DEBUG ): # pragma: NO COVER try: - response_payload = space.ListSpacesResponse.to_json(response) + response_payload = section.PositionSectionResponse.to_json(response) except: response_payload = None http_response = { @@ -5886,10 +7131,10 @@ def __call__( "status": response.status_code, } _LOGGER.debug( - "Received response for google.chat_v1.ChatServiceClient.list_spaces", + "Received response for google.chat_v1.ChatServiceClient.position_section", extra={ "serviceName": "google.chat.v1.ChatService", - "rpcName": "ListSpaces", + "rpcName": "PositionSection", "metadata": http_response["headers"], "httpResponse": http_response, }, @@ -6518,6 +7763,181 @@ def __call__( ) return resp + class _UpdateSection( + _BaseChatServiceRestTransport._BaseUpdateSection, ChatServiceRestStub + ): + def __hash__(self): + return hash("ChatServiceRestTransport.UpdateSection") + + @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: gc_section.UpdateSectionRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> gc_section.Section: + r"""Call the update section method over HTTP. + + Args: + request (~.gc_section.UpdateSectionRequest): + The request object. Request message for updating a + section. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.gc_section.Section: + Represents a + `section `__ + in Google Chat. Sections help users organize their + spaces. There are two types of sections: + + 1. **System Sections:** These are predefined sections + managed by Google Chat. Their resource names are + fixed, and they cannot be created, deleted, or have + their ``display_name`` modified. Examples include: + + - ``users/{user}/sections/default-direct-messages`` + - ``users/{user}/sections/default-spaces`` + - ``users/{user}/sections/default-apps`` + + 2. **Custom Sections:** These are sections created and + managed by the user. Creating a custom section using + ``CreateSection`` **requires** a ``display_name``. + Custom sections can be updated using + ``UpdateSection`` and deleted using + ``DeleteSection``. + + """ + + http_options = ( + _BaseChatServiceRestTransport._BaseUpdateSection._get_http_options() + ) + + request, metadata = self._interceptor.pre_update_section(request, metadata) + transcoded_request = _BaseChatServiceRestTransport._BaseUpdateSection._get_transcoded_request( + http_options, request + ) + + body = ( + _BaseChatServiceRestTransport._BaseUpdateSection._get_request_body_json( + transcoded_request + ) + ) + + # Jsonify the query params + query_params = ( + _BaseChatServiceRestTransport._BaseUpdateSection._get_query_params_json( + transcoded_request + ) + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.chat_v1.ChatServiceClient.UpdateSection", + extra={ + "serviceName": "google.chat.v1.ChatService", + "rpcName": "UpdateSection", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = ChatServiceRestTransport._UpdateSection._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 = gc_section.Section() + pb_resp = gc_section.Section.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_update_section(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_update_section_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = gc_section.Section.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.chat_v1.ChatServiceClient.update_section", + extra={ + "serviceName": "google.chat.v1.ChatService", + "rpcName": "UpdateSection", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + class _UpdateSpace( _BaseChatServiceRestTransport._BaseUpdateSpace, ChatServiceRestStub ): @@ -7195,6 +8615,14 @@ def create_reaction( # In C++ this would require a dynamic_cast return self._CreateReaction(self._session, self._host, self._interceptor) # type: ignore + @property + def create_section( + self, + ) -> Callable[[gc_section.CreateSectionRequest], gc_section.Section]: + # 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._CreateSection(self._session, self._host, self._interceptor) # type: ignore + @property def create_space(self) -> Callable[[gc_space.CreateSpaceRequest], gc_space.Space]: # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. @@ -7233,6 +8661,14 @@ def delete_reaction( # In C++ this would require a dynamic_cast return self._DeleteReaction(self._session, self._host, self._interceptor) # type: ignore + @property + def delete_section( + self, + ) -> Callable[[section.DeleteSectionRequest], 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._DeleteSection(self._session, self._host, self._interceptor) # type: ignore + @property def delete_space(self) -> Callable[[space.DeleteSpaceRequest], empty_pb2.Empty]: # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. @@ -7360,6 +8796,22 @@ def list_reactions( # In C++ this would require a dynamic_cast return self._ListReactions(self._session, self._host, self._interceptor) # type: ignore + @property + def list_section_items( + self, + ) -> Callable[[section.ListSectionItemsRequest], section.ListSectionItemsResponse]: + # 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._ListSectionItems(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_sections( + self, + ) -> Callable[[section.ListSectionsRequest], section.ListSectionsResponse]: + # 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._ListSections(self._session, self._host, self._interceptor) # type: ignore + @property def list_space_events( self, @@ -7378,6 +8830,22 @@ def list_spaces( # In C++ this would require a dynamic_cast return self._ListSpaces(self._session, self._host, self._interceptor) # type: ignore + @property + def move_section_item( + self, + ) -> Callable[[section.MoveSectionItemRequest], section.MoveSectionItemResponse]: + # 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._MoveSectionItem(self._session, self._host, self._interceptor) # type: ignore + + @property + def position_section( + self, + ) -> Callable[[section.PositionSectionRequest], section.PositionSectionResponse]: + # 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._PositionSection(self._session, self._host, self._interceptor) # type: ignore + @property def search_spaces( self, @@ -7408,6 +8876,14 @@ def update_message( # In C++ this would require a dynamic_cast return self._UpdateMessage(self._session, self._host, self._interceptor) # type: ignore + @property + def update_section( + self, + ) -> Callable[[gc_section.UpdateSectionRequest], gc_section.Section]: + # 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._UpdateSection(self._session, self._host, self._interceptor) # type: ignore + @property def update_space(self) -> Callable[[gc_space.UpdateSpaceRequest], gc_space.Space]: # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. diff --git a/packages/google-apps-chat/google/apps/chat_v1/services/chat_service/transports/rest_base.py b/packages/google-apps-chat/google/apps/chat_v1/services/chat_service/transports/rest_base.py index 096dc810d09c..683a9f1fe395 100644 --- a/packages/google-apps-chat/google/apps/chat_v1/services/chat_service/transports/rest_base.py +++ b/packages/google-apps-chat/google/apps/chat_v1/services/chat_service/transports/rest_base.py @@ -26,6 +26,7 @@ membership, message, reaction, + section, space, space_event, space_notification_setting, @@ -36,6 +37,7 @@ from google.apps.chat_v1.types import membership as gc_membership from google.apps.chat_v1.types import message as gc_message from google.apps.chat_v1.types import reaction as gc_reaction +from google.apps.chat_v1.types import section as gc_section from google.apps.chat_v1.types import space as gc_space from google.apps.chat_v1.types import ( space_notification_setting as gc_space_notification_setting, @@ -392,6 +394,63 @@ def _get_query_params_json(transcoded_request): query_params["$alt"] = "json;enum-encoding=int" return query_params + class _BaseCreateSection: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1/{parent=users/*}/sections", + "body": "section", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = gc_section.CreateSectionRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseChatServiceRestTransport._BaseCreateSection._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + class _BaseCreateSpace: def __hash__(self): # pragma: NO COVER return NotImplementedError("__hash__ must be implemented.") @@ -637,6 +696,53 @@ def _get_query_params_json(transcoded_request): query_params["$alt"] = "json;enum-encoding=int" return query_params + class _BaseDeleteSection: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "delete", + "uri": "/v1/{name=users/*/sections/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = section.DeleteSectionRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseChatServiceRestTransport._BaseDeleteSection._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + class _BaseDeleteSpace: def __hash__(self): # pragma: NO COVER return NotImplementedError("__hash__ must be implemented.") @@ -1333,6 +1439,100 @@ def _get_query_params_json(transcoded_request): query_params["$alt"] = "json;enum-encoding=int" return query_params + class _BaseListSectionItems: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{parent=users/*/sections/*}/items", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = section.ListSectionItemsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseChatServiceRestTransport._BaseListSectionItems._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseListSections: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{parent=users/*}/sections", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = section.ListSectionsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseChatServiceRestTransport._BaseListSections._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + class _BaseListSpaceEvents: def __hash__(self): # pragma: NO COVER return NotImplementedError("__hash__ must be implemented.") @@ -1414,6 +1614,120 @@ def _get_query_params_json(transcoded_request): query_params["$alt"] = "json;enum-encoding=int" return query_params + class _BaseMoveSectionItem: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1/{name=users/*/sections/*/items/*}:move", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = section.MoveSectionItemRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseChatServiceRestTransport._BaseMoveSectionItem._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BasePositionSection: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1/{name=users/*/sections/*}:position", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = section.PositionSectionRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseChatServiceRestTransport._BasePositionSection._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + class _BaseSearchSpaces: def __hash__(self): # pragma: NO COVER return NotImplementedError("__hash__ must be implemented.") @@ -1643,6 +1957,65 @@ def _get_query_params_json(transcoded_request): query_params["$alt"] = "json;enum-encoding=int" return query_params + class _BaseUpdateSection: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "updateMask": {}, + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "patch", + "uri": "/v1/{section.name=users/*/sections/*}", + "body": "section", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = gc_section.UpdateSectionRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseChatServiceRestTransport._BaseUpdateSection._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + class _BaseUpdateSpace: def __hash__(self): # pragma: NO COVER return NotImplementedError("__hash__ must be implemented.") 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 5d3e0c542903..c68178f3e922 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 @@ -114,6 +114,21 @@ ListReactionsResponse, Reaction, ) +from .section import ( + CreateSectionRequest, + DeleteSectionRequest, + ListSectionItemsRequest, + ListSectionItemsResponse, + ListSectionsRequest, + ListSectionsResponse, + MoveSectionItemRequest, + MoveSectionItemResponse, + PositionSectionRequest, + PositionSectionResponse, + Section, + SectionItem, + UpdateSectionRequest, +) from .slash_command import ( SlashCommand, ) @@ -239,6 +254,19 @@ "ListReactionsRequest", "ListReactionsResponse", "Reaction", + "CreateSectionRequest", + "DeleteSectionRequest", + "ListSectionItemsRequest", + "ListSectionItemsResponse", + "ListSectionsRequest", + "ListSectionsResponse", + "MoveSectionItemRequest", + "MoveSectionItemResponse", + "PositionSectionRequest", + "PositionSectionResponse", + "Section", + "SectionItem", + "UpdateSectionRequest", "SlashCommand", "CompleteImportSpaceRequest", "CompleteImportSpaceResponse", diff --git a/packages/google-apps-chat/google/apps/chat_v1/types/section.py b/packages/google-apps-chat/google/apps/chat_v1/types/section.py new file mode 100644 index 000000000000..37f790cdfbb5 --- /dev/null +++ b/packages/google-apps-chat/google/apps/chat_v1/types/section.py @@ -0,0 +1,523 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore +import proto # type: ignore + +__protobuf__ = proto.module( + package="google.chat.v1", + manifest={ + "Section", + "SectionItem", + "CreateSectionRequest", + "DeleteSectionRequest", + "UpdateSectionRequest", + "ListSectionsRequest", + "ListSectionsResponse", + "PositionSectionRequest", + "PositionSectionResponse", + "ListSectionItemsRequest", + "ListSectionItemsResponse", + "MoveSectionItemRequest", + "MoveSectionItemResponse", + }, +) + + +class Section(proto.Message): + r"""Represents a + `section `__ in + Google Chat. Sections help users organize their spaces. There are + two types of sections: + + 1. **System Sections:** These are predefined sections managed by + Google Chat. Their resource names are fixed, and they cannot be + created, deleted, or have their ``display_name`` modified. + Examples include: + + - ``users/{user}/sections/default-direct-messages`` + - ``users/{user}/sections/default-spaces`` + - ``users/{user}/sections/default-apps`` + + 2. **Custom Sections:** These are sections created and managed by + the user. Creating a custom section using ``CreateSection`` + **requires** a ``display_name``. Custom sections can be updated + using ``UpdateSection`` and deleted using ``DeleteSection``. + + Attributes: + name (str): + Identifier. Resource name of the section. + + For system sections, the section ID is a constant string: + + - DEFAULT_DIRECT_MESSAGES: + ``users/{user}/sections/default-direct-messages`` + - DEFAULT_SPACES: ``users/{user}/sections/default-spaces`` + - DEFAULT_APPS: ``users/{user}/sections/default-apps`` + + Format: ``users/{user}/sections/{section}`` + display_name (str): + Optional. The section's display name. Only populated for + sections of type ``CUSTOM_SECTION``. Supports up to 80 + characters. Required when creating a ``CUSTOM_SECTION``. + sort_order (int): + Output only. The order of the section in relation to other + sections. Sections with a lower ``sort_order`` value appear + before sections with a higher value. + type_ (google.apps.chat_v1.types.Section.SectionType): + Required. The type of the section. + """ + + class SectionType(proto.Enum): + r"""Section types. + + Values: + SECTION_TYPE_UNSPECIFIED (0): + Unspecified section type. + CUSTOM_SECTION (1): + Custom section. + DEFAULT_DIRECT_MESSAGES (2): + Default section containing + `DIRECT_MESSAGE `__ + between two human users or + `GROUP_CHAT `__ + spaces that don't belong to any custom section. + DEFAULT_SPACES (3): + Default spaces that don't belong to any + custom section. + DEFAULT_APPS (6): + Default section containing a user's installed + apps. + """ + + SECTION_TYPE_UNSPECIFIED = 0 + CUSTOM_SECTION = 1 + DEFAULT_DIRECT_MESSAGES = 2 + DEFAULT_SPACES = 3 + DEFAULT_APPS = 6 + + name: str = proto.Field( + proto.STRING, + number=1, + ) + display_name: str = proto.Field( + proto.STRING, + number=2, + ) + sort_order: int = proto.Field( + proto.INT32, + number=3, + ) + type_: SectionType = proto.Field( + proto.ENUM, + number=4, + enum=SectionType, + ) + + +class SectionItem(proto.Message): + r"""A user's defined section item. This is used to represent + section items, such as spaces, grouped under a section. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + name (str): + Identifier. The resource name of the section item. + + Format: ``users/{user}/sections/{section}/items/{item}`` + space (str): + Optional. The space resource name. + + Format: ``spaces/{space}`` + + This field is a member of `oneof`_ ``item``. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + space: str = proto.Field( + proto.STRING, + number=2, + oneof="item", + ) + + +class CreateSectionRequest(proto.Message): + r"""Request message for creating a section. + + Attributes: + parent (str): + Required. The parent resource name where the section is + created. + + Format: ``users/{user}`` + section (google.apps.chat_v1.types.Section): + Required. The section to create. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + section: "Section" = proto.Field( + proto.MESSAGE, + number=2, + message="Section", + ) + + +class DeleteSectionRequest(proto.Message): + r"""Request message for deleting a section. `Developer + Preview `__. + + Attributes: + name (str): + Required. The name of the section to delete. + + Format: ``users/{user}/sections/{section}`` + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class UpdateSectionRequest(proto.Message): + r"""Request message for updating a section. + + Attributes: + section (google.apps.chat_v1.types.Section): + Required. The section to update. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. The mask to specify which fields to update. + + Currently supported field paths: + + - ``display_name`` + """ + + section: "Section" = proto.Field( + proto.MESSAGE, + number=1, + message="Section", + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class ListSectionsRequest(proto.Message): + r"""Request message for listing sections. + + Attributes: + parent (str): + Required. The parent, which is the user resource name that + owns this collection of sections. Only supports listing + sections for the calling user. To refer to the calling user, + set one of the following: + + - The ``me`` alias. For example, ``users/me``. + + - Their Workspace email address. For example, + ``users/user@example.com``. + + - Their user id. For example, ``users/123456789``. + + Format: ``users/{user}`` + page_size (int): + Optional. The maximum number of sections to return. The + service may return fewer than this value. + + If unspecified, at most 10 sections will be returned. + + The maximum value is 100. If you use a value more than 100, + it's automatically changed to 100. + + Negative values return an ``INVALID_ARGUMENT`` error. + page_token (str): + Optional. A page token, received from a + previous list sections call. Provide this to + retrieve the subsequent page. + + When paginating, all other parameters provided + should match the call that provided the page + token. Passing different values to the other + parameters might lead to unexpected 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, + ) + + +class ListSectionsResponse(proto.Message): + r"""Response message for listing sections. + + Attributes: + sections (MutableSequence[google.apps.chat_v1.types.Section]): + The sections from the specified user. + 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 + + sections: MutableSequence["Section"] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message="Section", + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class PositionSectionRequest(proto.Message): + r"""Request message for positioning a section. + + 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: + name (str): + Required. The resource name of the section to position. + + Format: ``users/{user}/sections/{section}`` + sort_order (int): + Optional. The absolute position of the + section in the list of sections. The position + must be greater than 0. If the position is + greater than the number of sections, the section + will be appended to the end of the list. This + operation inserts the section at the given + position and shifts the original section at that + position, and those below it, to the next + position. + + This field is a member of `oneof`_ ``position``. + relative_position (google.apps.chat_v1.types.PositionSectionRequest.Position): + Optional. The relative position of the + section in the list of sections. + + This field is a member of `oneof`_ ``position``. + """ + + class Position(proto.Enum): + r"""The position of the section. + + Values: + POSITION_UNSPECIFIED (0): + Unspecified position. + START (1): + Start of the list of sections. + END (2): + End of the list of sections. + """ + + POSITION_UNSPECIFIED = 0 + START = 1 + END = 2 + + name: str = proto.Field( + proto.STRING, + number=1, + ) + sort_order: int = proto.Field( + proto.INT32, + number=2, + oneof="position", + ) + relative_position: Position = proto.Field( + proto.ENUM, + number=3, + oneof="position", + enum=Position, + ) + + +class PositionSectionResponse(proto.Message): + r"""Response message for positioning a section. + + Attributes: + section (google.apps.chat_v1.types.Section): + The updated section. + """ + + section: "Section" = proto.Field( + proto.MESSAGE, + number=1, + message="Section", + ) + + +class ListSectionItemsRequest(proto.Message): + r"""Request message for listing section items. + + Attributes: + parent (str): + Required. The parent, which is the section resource name + that owns this collection of section items. Only supports + listing section items for the calling user. + + When you're filtering by space, use the wildcard ``-`` to + search across all sections. For example, + ``users/{user}/sections/-``. + + Format: ``users/{user}/sections/{section}`` + page_size (int): + Optional. The maximum number of section items to return. The + service may return fewer than this value. + + If unspecified, at most 10 section items will be returned. + + The maximum value is 100. If you use a value more than 100, + it's automatically changed to 100. + + Negative values return an ``INVALID_ARGUMENT`` error. + page_token (str): + Optional. A page token, received from a + previous list section items call. Provide this + to retrieve the subsequent page. + + When paginating, all other parameters provided + should match the call that provided the page + token. Passing different values to the other + parameters might lead to unexpected results. + filter (str): + Optional. A query filter. + + Currently only supports filtering by space. + + For example, ``space = spaces/{space}``. + + Invalid queries are rejected with an ``INVALID_ARGUMENT`` + error. + """ + + 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 ListSectionItemsResponse(proto.Message): + r"""Response message for listing section items. + + Attributes: + section_items (MutableSequence[google.apps.chat_v1.types.SectionItem]): + The section items from the specified section. + 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 + + section_items: MutableSequence["SectionItem"] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message="SectionItem", + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class MoveSectionItemRequest(proto.Message): + r"""Request message for moving a section item across sections. + + Attributes: + name (str): + Required. The resource name of the section item to move. + + Format: ``users/{user}/sections/{section}/items/{item}`` + target_section (str): + Required. The resource name of the section to move the + section item to. + + Format: ``users/{user}/sections/{section}`` + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + target_section: str = proto.Field( + proto.STRING, + number=2, + ) + + +class MoveSectionItemResponse(proto.Message): + r"""Response message for moving a section item. + + Attributes: + section_item (google.apps.chat_v1.types.SectionItem): + The updated section item. + """ + + section_item: "SectionItem" = proto.Field( + proto.MESSAGE, + number=1, + message="SectionItem", + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-apps-chat/samples/generated_samples/chat_v1_generated_chat_service_create_section_async.py b/packages/google-apps-chat/samples/generated_samples/chat_v1_generated_chat_service_create_section_async.py new file mode 100644 index 000000000000..2bc63ec45363 --- /dev/null +++ b/packages/google-apps-chat/samples/generated_samples/chat_v1_generated_chat_service_create_section_async.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateSection +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-apps-chat + + +# [START chat_v1_generated_ChatService_CreateSection_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.apps import chat_v1 + + +async def sample_create_section(): + # Create a client + client = chat_v1.ChatServiceAsyncClient() + + # Initialize request argument(s) + section = chat_v1.Section() + section.type_ = "DEFAULT_APPS" + + request = chat_v1.CreateSectionRequest( + parent="parent_value", + section=section, + ) + + # Make the request + response = await client.create_section(request=request) + + # Handle the response + print(response) + + +# [END chat_v1_generated_ChatService_CreateSection_async] diff --git a/packages/google-apps-chat/samples/generated_samples/chat_v1_generated_chat_service_create_section_sync.py b/packages/google-apps-chat/samples/generated_samples/chat_v1_generated_chat_service_create_section_sync.py new file mode 100644 index 000000000000..92f67a4c69ac --- /dev/null +++ b/packages/google-apps-chat/samples/generated_samples/chat_v1_generated_chat_service_create_section_sync.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateSection +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-apps-chat + + +# [START chat_v1_generated_ChatService_CreateSection_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.apps import chat_v1 + + +def sample_create_section(): + # Create a client + client = chat_v1.ChatServiceClient() + + # Initialize request argument(s) + section = chat_v1.Section() + section.type_ = "DEFAULT_APPS" + + request = chat_v1.CreateSectionRequest( + parent="parent_value", + section=section, + ) + + # Make the request + response = client.create_section(request=request) + + # Handle the response + print(response) + + +# [END chat_v1_generated_ChatService_CreateSection_sync] diff --git a/packages/google-apps-chat/samples/generated_samples/chat_v1_generated_chat_service_delete_section_async.py b/packages/google-apps-chat/samples/generated_samples/chat_v1_generated_chat_service_delete_section_async.py new file mode 100644 index 000000000000..d9df29b7bb49 --- /dev/null +++ b/packages/google-apps-chat/samples/generated_samples/chat_v1_generated_chat_service_delete_section_async.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteSection +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-apps-chat + + +# [START chat_v1_generated_ChatService_DeleteSection_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.apps import chat_v1 + + +async def sample_delete_section(): + # Create a client + client = chat_v1.ChatServiceAsyncClient() + + # Initialize request argument(s) + request = chat_v1.DeleteSectionRequest( + name="name_value", + ) + + # Make the request + await client.delete_section(request=request) + + +# [END chat_v1_generated_ChatService_DeleteSection_async] diff --git a/packages/google-apps-chat/samples/generated_samples/chat_v1_generated_chat_service_delete_section_sync.py b/packages/google-apps-chat/samples/generated_samples/chat_v1_generated_chat_service_delete_section_sync.py new file mode 100644 index 000000000000..3b7748743494 --- /dev/null +++ b/packages/google-apps-chat/samples/generated_samples/chat_v1_generated_chat_service_delete_section_sync.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteSection +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-apps-chat + + +# [START chat_v1_generated_ChatService_DeleteSection_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.apps import chat_v1 + + +def sample_delete_section(): + # Create a client + client = chat_v1.ChatServiceClient() + + # Initialize request argument(s) + request = chat_v1.DeleteSectionRequest( + name="name_value", + ) + + # Make the request + client.delete_section(request=request) + + +# [END chat_v1_generated_ChatService_DeleteSection_sync] diff --git a/packages/google-apps-chat/samples/generated_samples/chat_v1_generated_chat_service_list_section_items_async.py b/packages/google-apps-chat/samples/generated_samples/chat_v1_generated_chat_service_list_section_items_async.py new file mode 100644 index 000000000000..632f2f5019dc --- /dev/null +++ b/packages/google-apps-chat/samples/generated_samples/chat_v1_generated_chat_service_list_section_items_async.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListSectionItems +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-apps-chat + + +# [START chat_v1_generated_ChatService_ListSectionItems_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.apps import chat_v1 + + +async def sample_list_section_items(): + # Create a client + client = chat_v1.ChatServiceAsyncClient() + + # Initialize request argument(s) + request = chat_v1.ListSectionItemsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_section_items(request=request) + + # Handle the response + async for response in page_result: + print(response) + + +# [END chat_v1_generated_ChatService_ListSectionItems_async] diff --git a/packages/google-apps-chat/samples/generated_samples/chat_v1_generated_chat_service_list_section_items_sync.py b/packages/google-apps-chat/samples/generated_samples/chat_v1_generated_chat_service_list_section_items_sync.py new file mode 100644 index 000000000000..a6519c8b7c40 --- /dev/null +++ b/packages/google-apps-chat/samples/generated_samples/chat_v1_generated_chat_service_list_section_items_sync.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListSectionItems +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-apps-chat + + +# [START chat_v1_generated_ChatService_ListSectionItems_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.apps import chat_v1 + + +def sample_list_section_items(): + # Create a client + client = chat_v1.ChatServiceClient() + + # Initialize request argument(s) + request = chat_v1.ListSectionItemsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_section_items(request=request) + + # Handle the response + for response in page_result: + print(response) + + +# [END chat_v1_generated_ChatService_ListSectionItems_sync] diff --git a/packages/google-apps-chat/samples/generated_samples/chat_v1_generated_chat_service_list_sections_async.py b/packages/google-apps-chat/samples/generated_samples/chat_v1_generated_chat_service_list_sections_async.py new file mode 100644 index 000000000000..0c437bec81f2 --- /dev/null +++ b/packages/google-apps-chat/samples/generated_samples/chat_v1_generated_chat_service_list_sections_async.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListSections +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-apps-chat + + +# [START chat_v1_generated_ChatService_ListSections_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.apps import chat_v1 + + +async def sample_list_sections(): + # Create a client + client = chat_v1.ChatServiceAsyncClient() + + # Initialize request argument(s) + request = chat_v1.ListSectionsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_sections(request=request) + + # Handle the response + async for response in page_result: + print(response) + + +# [END chat_v1_generated_ChatService_ListSections_async] diff --git a/packages/google-apps-chat/samples/generated_samples/chat_v1_generated_chat_service_list_sections_sync.py b/packages/google-apps-chat/samples/generated_samples/chat_v1_generated_chat_service_list_sections_sync.py new file mode 100644 index 000000000000..88df3a5f0719 --- /dev/null +++ b/packages/google-apps-chat/samples/generated_samples/chat_v1_generated_chat_service_list_sections_sync.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListSections +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-apps-chat + + +# [START chat_v1_generated_ChatService_ListSections_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.apps import chat_v1 + + +def sample_list_sections(): + # Create a client + client = chat_v1.ChatServiceClient() + + # Initialize request argument(s) + request = chat_v1.ListSectionsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_sections(request=request) + + # Handle the response + for response in page_result: + print(response) + + +# [END chat_v1_generated_ChatService_ListSections_sync] diff --git a/packages/google-apps-chat/samples/generated_samples/chat_v1_generated_chat_service_move_section_item_async.py b/packages/google-apps-chat/samples/generated_samples/chat_v1_generated_chat_service_move_section_item_async.py new file mode 100644 index 000000000000..951988ca6628 --- /dev/null +++ b/packages/google-apps-chat/samples/generated_samples/chat_v1_generated_chat_service_move_section_item_async.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for MoveSectionItem +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-apps-chat + + +# [START chat_v1_generated_ChatService_MoveSectionItem_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.apps import chat_v1 + + +async def sample_move_section_item(): + # Create a client + client = chat_v1.ChatServiceAsyncClient() + + # Initialize request argument(s) + request = chat_v1.MoveSectionItemRequest( + name="name_value", + target_section="target_section_value", + ) + + # Make the request + response = await client.move_section_item(request=request) + + # Handle the response + print(response) + + +# [END chat_v1_generated_ChatService_MoveSectionItem_async] diff --git a/packages/google-apps-chat/samples/generated_samples/chat_v1_generated_chat_service_move_section_item_sync.py b/packages/google-apps-chat/samples/generated_samples/chat_v1_generated_chat_service_move_section_item_sync.py new file mode 100644 index 000000000000..558363020b2a --- /dev/null +++ b/packages/google-apps-chat/samples/generated_samples/chat_v1_generated_chat_service_move_section_item_sync.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for MoveSectionItem +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-apps-chat + + +# [START chat_v1_generated_ChatService_MoveSectionItem_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.apps import chat_v1 + + +def sample_move_section_item(): + # Create a client + client = chat_v1.ChatServiceClient() + + # Initialize request argument(s) + request = chat_v1.MoveSectionItemRequest( + name="name_value", + target_section="target_section_value", + ) + + # Make the request + response = client.move_section_item(request=request) + + # Handle the response + print(response) + + +# [END chat_v1_generated_ChatService_MoveSectionItem_sync] diff --git a/packages/google-apps-chat/samples/generated_samples/chat_v1_generated_chat_service_position_section_async.py b/packages/google-apps-chat/samples/generated_samples/chat_v1_generated_chat_service_position_section_async.py new file mode 100644 index 000000000000..1d9dfb1dcdec --- /dev/null +++ b/packages/google-apps-chat/samples/generated_samples/chat_v1_generated_chat_service_position_section_async.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for PositionSection +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-apps-chat + + +# [START chat_v1_generated_ChatService_PositionSection_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.apps import chat_v1 + + +async def sample_position_section(): + # Create a client + client = chat_v1.ChatServiceAsyncClient() + + # Initialize request argument(s) + request = chat_v1.PositionSectionRequest( + sort_order=1091, + name="name_value", + ) + + # Make the request + response = await client.position_section(request=request) + + # Handle the response + print(response) + + +# [END chat_v1_generated_ChatService_PositionSection_async] diff --git a/packages/google-apps-chat/samples/generated_samples/chat_v1_generated_chat_service_position_section_sync.py b/packages/google-apps-chat/samples/generated_samples/chat_v1_generated_chat_service_position_section_sync.py new file mode 100644 index 000000000000..71efade6b5d7 --- /dev/null +++ b/packages/google-apps-chat/samples/generated_samples/chat_v1_generated_chat_service_position_section_sync.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for PositionSection +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-apps-chat + + +# [START chat_v1_generated_ChatService_PositionSection_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.apps import chat_v1 + + +def sample_position_section(): + # Create a client + client = chat_v1.ChatServiceClient() + + # Initialize request argument(s) + request = chat_v1.PositionSectionRequest( + sort_order=1091, + name="name_value", + ) + + # Make the request + response = client.position_section(request=request) + + # Handle the response + print(response) + + +# [END chat_v1_generated_ChatService_PositionSection_sync] diff --git a/packages/google-apps-chat/samples/generated_samples/chat_v1_generated_chat_service_update_section_async.py b/packages/google-apps-chat/samples/generated_samples/chat_v1_generated_chat_service_update_section_async.py new file mode 100644 index 000000000000..2f362ad74996 --- /dev/null +++ b/packages/google-apps-chat/samples/generated_samples/chat_v1_generated_chat_service_update_section_async.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateSection +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-apps-chat + + +# [START chat_v1_generated_ChatService_UpdateSection_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.apps import chat_v1 + + +async def sample_update_section(): + # Create a client + client = chat_v1.ChatServiceAsyncClient() + + # Initialize request argument(s) + section = chat_v1.Section() + section.type_ = "DEFAULT_APPS" + + request = chat_v1.UpdateSectionRequest( + section=section, + ) + + # Make the request + response = await client.update_section(request=request) + + # Handle the response + print(response) + + +# [END chat_v1_generated_ChatService_UpdateSection_async] diff --git a/packages/google-apps-chat/samples/generated_samples/chat_v1_generated_chat_service_update_section_sync.py b/packages/google-apps-chat/samples/generated_samples/chat_v1_generated_chat_service_update_section_sync.py new file mode 100644 index 000000000000..075c86c341e5 --- /dev/null +++ b/packages/google-apps-chat/samples/generated_samples/chat_v1_generated_chat_service_update_section_sync.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateSection +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-apps-chat + + +# [START chat_v1_generated_ChatService_UpdateSection_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.apps import chat_v1 + + +def sample_update_section(): + # Create a client + client = chat_v1.ChatServiceClient() + + # Initialize request argument(s) + section = chat_v1.Section() + section.type_ = "DEFAULT_APPS" + + request = chat_v1.UpdateSectionRequest( + section=section, + ) + + # Make the request + response = client.update_section(request=request) + + # Handle the response + print(response) + + +# [END chat_v1_generated_ChatService_UpdateSection_sync] diff --git a/packages/google-apps-chat/samples/generated_samples/snippet_metadata_google.chat.v1.json b/packages/google-apps-chat/samples/generated_samples/snippet_metadata_google.chat.v1.json index b22c6e22ce99..ecff63aa6c50 100644 --- a/packages/google-apps-chat/samples/generated_samples/snippet_metadata_google.chat.v1.json +++ b/packages/google-apps-chat/samples/generated_samples/snippet_metadata_google.chat.v1.json @@ -840,6 +840,175 @@ ], "title": "chat_v1_generated_chat_service_create_reaction_sync.py" }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.apps.chat_v1.ChatServiceAsyncClient", + "shortName": "ChatServiceAsyncClient" + }, + "fullName": "google.apps.chat_v1.ChatServiceAsyncClient.create_section", + "method": { + "fullName": "google.chat.v1.ChatService.CreateSection", + "service": { + "fullName": "google.chat.v1.ChatService", + "shortName": "ChatService" + }, + "shortName": "CreateSection" + }, + "parameters": [ + { + "name": "request", + "type": "google.apps.chat_v1.types.CreateSectionRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "section", + "type": "google.apps.chat_v1.types.Section" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.apps.chat_v1.types.Section", + "shortName": "create_section" + }, + "description": "Sample for CreateSection", + "file": "chat_v1_generated_chat_service_create_section_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "chat_v1_generated_ChatService_CreateSection_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": "chat_v1_generated_chat_service_create_section_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.apps.chat_v1.ChatServiceClient", + "shortName": "ChatServiceClient" + }, + "fullName": "google.apps.chat_v1.ChatServiceClient.create_section", + "method": { + "fullName": "google.chat.v1.ChatService.CreateSection", + "service": { + "fullName": "google.chat.v1.ChatService", + "shortName": "ChatService" + }, + "shortName": "CreateSection" + }, + "parameters": [ + { + "name": "request", + "type": "google.apps.chat_v1.types.CreateSectionRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "section", + "type": "google.apps.chat_v1.types.Section" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.apps.chat_v1.types.Section", + "shortName": "create_section" + }, + "description": "Sample for CreateSection", + "file": "chat_v1_generated_chat_service_create_section_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "chat_v1_generated_ChatService_CreateSection_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": "chat_v1_generated_chat_service_create_section_sync.py" + }, { "canonical": true, "clientMethod": { @@ -1635,19 +1804,19 @@ "fullName": "google.apps.chat_v1.ChatServiceAsyncClient", "shortName": "ChatServiceAsyncClient" }, - "fullName": "google.apps.chat_v1.ChatServiceAsyncClient.delete_space", + "fullName": "google.apps.chat_v1.ChatServiceAsyncClient.delete_section", "method": { - "fullName": "google.chat.v1.ChatService.DeleteSpace", + "fullName": "google.chat.v1.ChatService.DeleteSection", "service": { "fullName": "google.chat.v1.ChatService", "shortName": "ChatService" }, - "shortName": "DeleteSpace" + "shortName": "DeleteSection" }, "parameters": [ { "name": "request", - "type": "google.apps.chat_v1.types.DeleteSpaceRequest" + "type": "google.apps.chat_v1.types.DeleteSectionRequest" }, { "name": "name", @@ -1666,13 +1835,13 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "shortName": "delete_space" + "shortName": "delete_section" }, - "description": "Sample for DeleteSpace", - "file": "chat_v1_generated_chat_service_delete_space_async.py", + "description": "Sample for DeleteSection", + "file": "chat_v1_generated_chat_service_delete_section_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "chat_v1_generated_ChatService_DeleteSpace_async", + "regionTag": "chat_v1_generated_ChatService_DeleteSection_async", "segments": [ { "end": 49, @@ -1703,7 +1872,7 @@ "type": "RESPONSE_HANDLING" } ], - "title": "chat_v1_generated_chat_service_delete_space_async.py" + "title": "chat_v1_generated_chat_service_delete_section_async.py" }, { "canonical": true, @@ -1712,19 +1881,19 @@ "fullName": "google.apps.chat_v1.ChatServiceClient", "shortName": "ChatServiceClient" }, - "fullName": "google.apps.chat_v1.ChatServiceClient.delete_space", + "fullName": "google.apps.chat_v1.ChatServiceClient.delete_section", "method": { - "fullName": "google.chat.v1.ChatService.DeleteSpace", + "fullName": "google.chat.v1.ChatService.DeleteSection", "service": { "fullName": "google.chat.v1.ChatService", "shortName": "ChatService" }, - "shortName": "DeleteSpace" + "shortName": "DeleteSection" }, "parameters": [ { "name": "request", - "type": "google.apps.chat_v1.types.DeleteSpaceRequest" + "type": "google.apps.chat_v1.types.DeleteSectionRequest" }, { "name": "name", @@ -1743,13 +1912,13 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "shortName": "delete_space" + "shortName": "delete_section" }, - "description": "Sample for DeleteSpace", - "file": "chat_v1_generated_chat_service_delete_space_sync.py", + "description": "Sample for DeleteSection", + "file": "chat_v1_generated_chat_service_delete_section_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "chat_v1_generated_ChatService_DeleteSpace_sync", + "regionTag": "chat_v1_generated_ChatService_DeleteSection_sync", "segments": [ { "end": 49, @@ -1780,7 +1949,7 @@ "type": "RESPONSE_HANDLING" } ], - "title": "chat_v1_generated_chat_service_delete_space_sync.py" + "title": "chat_v1_generated_chat_service_delete_section_sync.py" }, { "canonical": true, @@ -1790,19 +1959,23 @@ "fullName": "google.apps.chat_v1.ChatServiceAsyncClient", "shortName": "ChatServiceAsyncClient" }, - "fullName": "google.apps.chat_v1.ChatServiceAsyncClient.find_direct_message", + "fullName": "google.apps.chat_v1.ChatServiceAsyncClient.delete_space", "method": { - "fullName": "google.chat.v1.ChatService.FindDirectMessage", + "fullName": "google.chat.v1.ChatService.DeleteSpace", "service": { "fullName": "google.chat.v1.ChatService", "shortName": "ChatService" }, - "shortName": "FindDirectMessage" + "shortName": "DeleteSpace" }, "parameters": [ { "name": "request", - "type": "google.apps.chat_v1.types.FindDirectMessageRequest" + "type": "google.apps.chat_v1.types.DeleteSpaceRequest" + }, + { + "name": "name", + "type": "str" }, { "name": "retry", @@ -1817,22 +1990,21 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.apps.chat_v1.types.Space", - "shortName": "find_direct_message" + "shortName": "delete_space" }, - "description": "Sample for FindDirectMessage", - "file": "chat_v1_generated_chat_service_find_direct_message_async.py", + "description": "Sample for DeleteSpace", + "file": "chat_v1_generated_chat_service_delete_space_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "chat_v1_generated_ChatService_FindDirectMessage_async", + "regionTag": "chat_v1_generated_ChatService_DeleteSpace_async", "segments": [ { - "end": 51, + "end": 49, "start": 27, "type": "FULL" }, { - "end": 51, + "end": 49, "start": 27, "type": "SHORT" }, @@ -1847,17 +2019,15 @@ "type": "REQUEST_INITIALIZATION" }, { - "end": 48, "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 52, - "start": 49, + "end": 50, "type": "RESPONSE_HANDLING" } ], - "title": "chat_v1_generated_chat_service_find_direct_message_async.py" + "title": "chat_v1_generated_chat_service_delete_space_async.py" }, { "canonical": true, @@ -1866,19 +2036,23 @@ "fullName": "google.apps.chat_v1.ChatServiceClient", "shortName": "ChatServiceClient" }, - "fullName": "google.apps.chat_v1.ChatServiceClient.find_direct_message", + "fullName": "google.apps.chat_v1.ChatServiceClient.delete_space", "method": { - "fullName": "google.chat.v1.ChatService.FindDirectMessage", + "fullName": "google.chat.v1.ChatService.DeleteSpace", "service": { "fullName": "google.chat.v1.ChatService", "shortName": "ChatService" }, - "shortName": "FindDirectMessage" + "shortName": "DeleteSpace" }, "parameters": [ { "name": "request", - "type": "google.apps.chat_v1.types.FindDirectMessageRequest" + "type": "google.apps.chat_v1.types.DeleteSpaceRequest" + }, + { + "name": "name", + "type": "str" }, { "name": "retry", @@ -1893,22 +2067,21 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.apps.chat_v1.types.Space", - "shortName": "find_direct_message" + "shortName": "delete_space" }, - "description": "Sample for FindDirectMessage", - "file": "chat_v1_generated_chat_service_find_direct_message_sync.py", + "description": "Sample for DeleteSpace", + "file": "chat_v1_generated_chat_service_delete_space_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "chat_v1_generated_ChatService_FindDirectMessage_sync", + "regionTag": "chat_v1_generated_ChatService_DeleteSpace_sync", "segments": [ { - "end": 51, + "end": 49, "start": 27, "type": "FULL" }, { - "end": 51, + "end": 49, "start": 27, "type": "SHORT" }, @@ -1923,17 +2096,15 @@ "type": "REQUEST_INITIALIZATION" }, { - "end": 48, "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 52, - "start": 49, + "end": 50, "type": "RESPONSE_HANDLING" } ], - "title": "chat_v1_generated_chat_service_find_direct_message_sync.py" + "title": "chat_v1_generated_chat_service_delete_space_sync.py" }, { "canonical": true, @@ -1943,23 +2114,19 @@ "fullName": "google.apps.chat_v1.ChatServiceAsyncClient", "shortName": "ChatServiceAsyncClient" }, - "fullName": "google.apps.chat_v1.ChatServiceAsyncClient.get_attachment", + "fullName": "google.apps.chat_v1.ChatServiceAsyncClient.find_direct_message", "method": { - "fullName": "google.chat.v1.ChatService.GetAttachment", + "fullName": "google.chat.v1.ChatService.FindDirectMessage", "service": { "fullName": "google.chat.v1.ChatService", "shortName": "ChatService" }, - "shortName": "GetAttachment" + "shortName": "FindDirectMessage" }, "parameters": [ { "name": "request", - "type": "google.apps.chat_v1.types.GetAttachmentRequest" - }, - { - "name": "name", - "type": "str" + "type": "google.apps.chat_v1.types.FindDirectMessageRequest" }, { "name": "retry", @@ -1974,14 +2141,14 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.apps.chat_v1.types.Attachment", - "shortName": "get_attachment" + "resultType": "google.apps.chat_v1.types.Space", + "shortName": "find_direct_message" }, - "description": "Sample for GetAttachment", - "file": "chat_v1_generated_chat_service_get_attachment_async.py", + "description": "Sample for FindDirectMessage", + "file": "chat_v1_generated_chat_service_find_direct_message_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "chat_v1_generated_ChatService_GetAttachment_async", + "regionTag": "chat_v1_generated_ChatService_FindDirectMessage_async", "segments": [ { "end": 51, @@ -2014,7 +2181,7 @@ "type": "RESPONSE_HANDLING" } ], - "title": "chat_v1_generated_chat_service_get_attachment_async.py" + "title": "chat_v1_generated_chat_service_find_direct_message_async.py" }, { "canonical": true, @@ -2023,19 +2190,176 @@ "fullName": "google.apps.chat_v1.ChatServiceClient", "shortName": "ChatServiceClient" }, - "fullName": "google.apps.chat_v1.ChatServiceClient.get_attachment", + "fullName": "google.apps.chat_v1.ChatServiceClient.find_direct_message", "method": { - "fullName": "google.chat.v1.ChatService.GetAttachment", + "fullName": "google.chat.v1.ChatService.FindDirectMessage", "service": { "fullName": "google.chat.v1.ChatService", "shortName": "ChatService" }, - "shortName": "GetAttachment" + "shortName": "FindDirectMessage" }, "parameters": [ { "name": "request", - "type": "google.apps.chat_v1.types.GetAttachmentRequest" + "type": "google.apps.chat_v1.types.FindDirectMessageRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.apps.chat_v1.types.Space", + "shortName": "find_direct_message" + }, + "description": "Sample for FindDirectMessage", + "file": "chat_v1_generated_chat_service_find_direct_message_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "chat_v1_generated_ChatService_FindDirectMessage_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": "chat_v1_generated_chat_service_find_direct_message_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.apps.chat_v1.ChatServiceAsyncClient", + "shortName": "ChatServiceAsyncClient" + }, + "fullName": "google.apps.chat_v1.ChatServiceAsyncClient.get_attachment", + "method": { + "fullName": "google.chat.v1.ChatService.GetAttachment", + "service": { + "fullName": "google.chat.v1.ChatService", + "shortName": "ChatService" + }, + "shortName": "GetAttachment" + }, + "parameters": [ + { + "name": "request", + "type": "google.apps.chat_v1.types.GetAttachmentRequest" + }, + { + "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.apps.chat_v1.types.Attachment", + "shortName": "get_attachment" + }, + "description": "Sample for GetAttachment", + "file": "chat_v1_generated_chat_service_get_attachment_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "chat_v1_generated_ChatService_GetAttachment_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": "chat_v1_generated_chat_service_get_attachment_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.apps.chat_v1.ChatServiceClient", + "shortName": "ChatServiceClient" + }, + "fullName": "google.apps.chat_v1.ChatServiceClient.get_attachment", + "method": { + "fullName": "google.chat.v1.ChatService.GetAttachment", + "service": { + "fullName": "google.chat.v1.ChatService", + "shortName": "ChatService" + }, + "shortName": "GetAttachment" + }, + "parameters": [ + { + "name": "request", + "type": "google.apps.chat_v1.types.GetAttachmentRequest" }, { "name": "name", @@ -4028,28 +4352,24 @@ "fullName": "google.apps.chat_v1.ChatServiceAsyncClient", "shortName": "ChatServiceAsyncClient" }, - "fullName": "google.apps.chat_v1.ChatServiceAsyncClient.list_space_events", + "fullName": "google.apps.chat_v1.ChatServiceAsyncClient.list_section_items", "method": { - "fullName": "google.chat.v1.ChatService.ListSpaceEvents", + "fullName": "google.chat.v1.ChatService.ListSectionItems", "service": { "fullName": "google.chat.v1.ChatService", "shortName": "ChatService" }, - "shortName": "ListSpaceEvents" + "shortName": "ListSectionItems" }, "parameters": [ { "name": "request", - "type": "google.apps.chat_v1.types.ListSpaceEventsRequest" + "type": "google.apps.chat_v1.types.ListSectionItemsRequest" }, { "name": "parent", "type": "str" }, - { - "name": "filter", - "type": "str" - }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -4063,22 +4383,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.apps.chat_v1.services.chat_service.pagers.ListSpaceEventsAsyncPager", - "shortName": "list_space_events" + "resultType": "google.apps.chat_v1.services.chat_service.pagers.ListSectionItemsAsyncPager", + "shortName": "list_section_items" }, - "description": "Sample for ListSpaceEvents", - "file": "chat_v1_generated_chat_service_list_space_events_async.py", + "description": "Sample for ListSectionItems", + "file": "chat_v1_generated_chat_service_list_section_items_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "chat_v1_generated_ChatService_ListSpaceEvents_async", + "regionTag": "chat_v1_generated_ChatService_ListSectionItems_async", "segments": [ { - "end": 53, + "end": 52, "start": 27, "type": "FULL" }, { - "end": 53, + "end": 52, "start": 27, "type": "SHORT" }, @@ -4088,22 +4408,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": "chat_v1_generated_chat_service_list_space_events_async.py" + "title": "chat_v1_generated_chat_service_list_section_items_async.py" }, { "canonical": true, @@ -4112,28 +4432,24 @@ "fullName": "google.apps.chat_v1.ChatServiceClient", "shortName": "ChatServiceClient" }, - "fullName": "google.apps.chat_v1.ChatServiceClient.list_space_events", + "fullName": "google.apps.chat_v1.ChatServiceClient.list_section_items", "method": { - "fullName": "google.chat.v1.ChatService.ListSpaceEvents", + "fullName": "google.chat.v1.ChatService.ListSectionItems", "service": { "fullName": "google.chat.v1.ChatService", "shortName": "ChatService" }, - "shortName": "ListSpaceEvents" + "shortName": "ListSectionItems" }, "parameters": [ { "name": "request", - "type": "google.apps.chat_v1.types.ListSpaceEventsRequest" + "type": "google.apps.chat_v1.types.ListSectionItemsRequest" }, { "name": "parent", "type": "str" }, - { - "name": "filter", - "type": "str" - }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -4147,22 +4463,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.apps.chat_v1.services.chat_service.pagers.ListSpaceEventsPager", - "shortName": "list_space_events" + "resultType": "google.apps.chat_v1.services.chat_service.pagers.ListSectionItemsPager", + "shortName": "list_section_items" }, - "description": "Sample for ListSpaceEvents", - "file": "chat_v1_generated_chat_service_list_space_events_sync.py", + "description": "Sample for ListSectionItems", + "file": "chat_v1_generated_chat_service_list_section_items_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "chat_v1_generated_ChatService_ListSpaceEvents_sync", + "regionTag": "chat_v1_generated_ChatService_ListSectionItems_sync", "segments": [ { - "end": 53, + "end": 52, "start": 27, "type": "FULL" }, { - "end": 53, + "end": 52, "start": 27, "type": "SHORT" }, @@ -4172,22 +4488,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": "chat_v1_generated_chat_service_list_space_events_sync.py" + "title": "chat_v1_generated_chat_service_list_section_items_sync.py" }, { "canonical": true, @@ -4197,19 +4513,23 @@ "fullName": "google.apps.chat_v1.ChatServiceAsyncClient", "shortName": "ChatServiceAsyncClient" }, - "fullName": "google.apps.chat_v1.ChatServiceAsyncClient.list_spaces", + "fullName": "google.apps.chat_v1.ChatServiceAsyncClient.list_sections", "method": { - "fullName": "google.chat.v1.ChatService.ListSpaces", + "fullName": "google.chat.v1.ChatService.ListSections", "service": { "fullName": "google.chat.v1.ChatService", "shortName": "ChatService" }, - "shortName": "ListSpaces" + "shortName": "ListSections" }, "parameters": [ { "name": "request", - "type": "google.apps.chat_v1.types.ListSpacesRequest" + "type": "google.apps.chat_v1.types.ListSectionsRequest" + }, + { + "name": "parent", + "type": "str" }, { "name": "retry", @@ -4224,22 +4544,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.apps.chat_v1.services.chat_service.pagers.ListSpacesAsyncPager", - "shortName": "list_spaces" + "resultType": "google.apps.chat_v1.services.chat_service.pagers.ListSectionsAsyncPager", + "shortName": "list_sections" }, - "description": "Sample for ListSpaces", - "file": "chat_v1_generated_chat_service_list_spaces_async.py", + "description": "Sample for ListSections", + "file": "chat_v1_generated_chat_service_list_sections_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "chat_v1_generated_ChatService_ListSpaces_async", + "regionTag": "chat_v1_generated_ChatService_ListSections_async", "segments": [ { - "end": 51, + "end": 52, "start": 27, "type": "FULL" }, { - "end": 51, + "end": 52, "start": 27, "type": "SHORT" }, @@ -4249,22 +4569,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": 52, - "start": 48, + "end": 53, + "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "chat_v1_generated_chat_service_list_spaces_async.py" + "title": "chat_v1_generated_chat_service_list_sections_async.py" }, { "canonical": true, @@ -4273,19 +4593,23 @@ "fullName": "google.apps.chat_v1.ChatServiceClient", "shortName": "ChatServiceClient" }, - "fullName": "google.apps.chat_v1.ChatServiceClient.list_spaces", + "fullName": "google.apps.chat_v1.ChatServiceClient.list_sections", "method": { - "fullName": "google.chat.v1.ChatService.ListSpaces", + "fullName": "google.chat.v1.ChatService.ListSections", "service": { "fullName": "google.chat.v1.ChatService", "shortName": "ChatService" }, - "shortName": "ListSpaces" + "shortName": "ListSections" }, "parameters": [ { "name": "request", - "type": "google.apps.chat_v1.types.ListSpacesRequest" + "type": "google.apps.chat_v1.types.ListSectionsRequest" + }, + { + "name": "parent", + "type": "str" }, { "name": "retry", @@ -4300,22 +4624,590 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.apps.chat_v1.services.chat_service.pagers.ListSpacesPager", - "shortName": "list_spaces" + "resultType": "google.apps.chat_v1.services.chat_service.pagers.ListSectionsPager", + "shortName": "list_sections" }, - "description": "Sample for ListSpaces", - "file": "chat_v1_generated_chat_service_list_spaces_sync.py", + "description": "Sample for ListSections", + "file": "chat_v1_generated_chat_service_list_sections_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "chat_v1_generated_ChatService_ListSpaces_sync", + "regionTag": "chat_v1_generated_ChatService_ListSections_sync", "segments": [ { - "end": 51, + "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": "chat_v1_generated_chat_service_list_sections_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.apps.chat_v1.ChatServiceAsyncClient", + "shortName": "ChatServiceAsyncClient" + }, + "fullName": "google.apps.chat_v1.ChatServiceAsyncClient.list_space_events", + "method": { + "fullName": "google.chat.v1.ChatService.ListSpaceEvents", + "service": { + "fullName": "google.chat.v1.ChatService", + "shortName": "ChatService" + }, + "shortName": "ListSpaceEvents" + }, + "parameters": [ + { + "name": "request", + "type": "google.apps.chat_v1.types.ListSpaceEventsRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "filter", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.apps.chat_v1.services.chat_service.pagers.ListSpaceEventsAsyncPager", + "shortName": "list_space_events" + }, + "description": "Sample for ListSpaceEvents", + "file": "chat_v1_generated_chat_service_list_space_events_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "chat_v1_generated_ChatService_ListSpaceEvents_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": "chat_v1_generated_chat_service_list_space_events_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.apps.chat_v1.ChatServiceClient", + "shortName": "ChatServiceClient" + }, + "fullName": "google.apps.chat_v1.ChatServiceClient.list_space_events", + "method": { + "fullName": "google.chat.v1.ChatService.ListSpaceEvents", + "service": { + "fullName": "google.chat.v1.ChatService", + "shortName": "ChatService" + }, + "shortName": "ListSpaceEvents" + }, + "parameters": [ + { + "name": "request", + "type": "google.apps.chat_v1.types.ListSpaceEventsRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "filter", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.apps.chat_v1.services.chat_service.pagers.ListSpaceEventsPager", + "shortName": "list_space_events" + }, + "description": "Sample for ListSpaceEvents", + "file": "chat_v1_generated_chat_service_list_space_events_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "chat_v1_generated_ChatService_ListSpaceEvents_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": "chat_v1_generated_chat_service_list_space_events_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.apps.chat_v1.ChatServiceAsyncClient", + "shortName": "ChatServiceAsyncClient" + }, + "fullName": "google.apps.chat_v1.ChatServiceAsyncClient.list_spaces", + "method": { + "fullName": "google.chat.v1.ChatService.ListSpaces", + "service": { + "fullName": "google.chat.v1.ChatService", + "shortName": "ChatService" + }, + "shortName": "ListSpaces" + }, + "parameters": [ + { + "name": "request", + "type": "google.apps.chat_v1.types.ListSpacesRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.apps.chat_v1.services.chat_service.pagers.ListSpacesAsyncPager", + "shortName": "list_spaces" + }, + "description": "Sample for ListSpaces", + "file": "chat_v1_generated_chat_service_list_spaces_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "chat_v1_generated_ChatService_ListSpaces_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 47, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 48, + "type": "RESPONSE_HANDLING" + } + ], + "title": "chat_v1_generated_chat_service_list_spaces_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.apps.chat_v1.ChatServiceClient", + "shortName": "ChatServiceClient" + }, + "fullName": "google.apps.chat_v1.ChatServiceClient.list_spaces", + "method": { + "fullName": "google.chat.v1.ChatService.ListSpaces", + "service": { + "fullName": "google.chat.v1.ChatService", + "shortName": "ChatService" + }, + "shortName": "ListSpaces" + }, + "parameters": [ + { + "name": "request", + "type": "google.apps.chat_v1.types.ListSpacesRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.apps.chat_v1.services.chat_service.pagers.ListSpacesPager", + "shortName": "list_spaces" + }, + "description": "Sample for ListSpaces", + "file": "chat_v1_generated_chat_service_list_spaces_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "chat_v1_generated_ChatService_ListSpaces_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 47, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 48, + "type": "RESPONSE_HANDLING" + } + ], + "title": "chat_v1_generated_chat_service_list_spaces_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.apps.chat_v1.ChatServiceAsyncClient", + "shortName": "ChatServiceAsyncClient" + }, + "fullName": "google.apps.chat_v1.ChatServiceAsyncClient.move_section_item", + "method": { + "fullName": "google.chat.v1.ChatService.MoveSectionItem", + "service": { + "fullName": "google.chat.v1.ChatService", + "shortName": "ChatService" + }, + "shortName": "MoveSectionItem" + }, + "parameters": [ + { + "name": "request", + "type": "google.apps.chat_v1.types.MoveSectionItemRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "target_section", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.apps.chat_v1.types.MoveSectionItemResponse", + "shortName": "move_section_item" + }, + "description": "Sample for MoveSectionItem", + "file": "chat_v1_generated_chat_service_move_section_item_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "chat_v1_generated_ChatService_MoveSectionItem_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": "chat_v1_generated_chat_service_move_section_item_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.apps.chat_v1.ChatServiceClient", + "shortName": "ChatServiceClient" + }, + "fullName": "google.apps.chat_v1.ChatServiceClient.move_section_item", + "method": { + "fullName": "google.chat.v1.ChatService.MoveSectionItem", + "service": { + "fullName": "google.chat.v1.ChatService", + "shortName": "ChatService" + }, + "shortName": "MoveSectionItem" + }, + "parameters": [ + { + "name": "request", + "type": "google.apps.chat_v1.types.MoveSectionItemRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "target_section", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.apps.chat_v1.types.MoveSectionItemResponse", + "shortName": "move_section_item" + }, + "description": "Sample for MoveSectionItem", + "file": "chat_v1_generated_chat_service_move_section_item_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "chat_v1_generated_ChatService_MoveSectionItem_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": "chat_v1_generated_chat_service_move_section_item_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.apps.chat_v1.ChatServiceAsyncClient", + "shortName": "ChatServiceAsyncClient" + }, + "fullName": "google.apps.chat_v1.ChatServiceAsyncClient.position_section", + "method": { + "fullName": "google.chat.v1.ChatService.PositionSection", + "service": { + "fullName": "google.chat.v1.ChatService", + "shortName": "ChatService" + }, + "shortName": "PositionSection" + }, + "parameters": [ + { + "name": "request", + "type": "google.apps.chat_v1.types.PositionSectionRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.apps.chat_v1.types.PositionSectionResponse", + "shortName": "position_section" + }, + "description": "Sample for PositionSection", + "file": "chat_v1_generated_chat_service_position_section_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "chat_v1_generated_ChatService_PositionSection_async", + "segments": [ + { + "end": 52, "start": 27, "type": "FULL" }, { - "end": 51, + "end": 52, "start": 27, "type": "SHORT" }, @@ -4325,22 +5217,98 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 44, + "end": 46, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 47, - "start": 45, + "end": 49, + "start": 47, "type": "REQUEST_EXECUTION" }, + { + "end": 53, + "start": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "chat_v1_generated_chat_service_position_section_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.apps.chat_v1.ChatServiceClient", + "shortName": "ChatServiceClient" + }, + "fullName": "google.apps.chat_v1.ChatServiceClient.position_section", + "method": { + "fullName": "google.chat.v1.ChatService.PositionSection", + "service": { + "fullName": "google.chat.v1.ChatService", + "shortName": "ChatService" + }, + "shortName": "PositionSection" + }, + "parameters": [ + { + "name": "request", + "type": "google.apps.chat_v1.types.PositionSectionRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.apps.chat_v1.types.PositionSectionResponse", + "shortName": "position_section" + }, + "description": "Sample for PositionSection", + "file": "chat_v1_generated_chat_service_position_section_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "chat_v1_generated_ChatService_PositionSection_sync", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, { "end": 52, - "start": 48, + "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": "chat_v1_generated_chat_service_list_spaces_sync.py" + "title": "chat_v1_generated_chat_service_position_section_sync.py" }, { "canonical": true, @@ -4986,6 +5954,175 @@ ], "title": "chat_v1_generated_chat_service_update_message_sync.py" }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.apps.chat_v1.ChatServiceAsyncClient", + "shortName": "ChatServiceAsyncClient" + }, + "fullName": "google.apps.chat_v1.ChatServiceAsyncClient.update_section", + "method": { + "fullName": "google.chat.v1.ChatService.UpdateSection", + "service": { + "fullName": "google.chat.v1.ChatService", + "shortName": "ChatService" + }, + "shortName": "UpdateSection" + }, + "parameters": [ + { + "name": "request", + "type": "google.apps.chat_v1.types.UpdateSectionRequest" + }, + { + "name": "section", + "type": "google.apps.chat_v1.types.Section" + }, + { + "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.apps.chat_v1.types.Section", + "shortName": "update_section" + }, + "description": "Sample for UpdateSection", + "file": "chat_v1_generated_chat_service_update_section_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "chat_v1_generated_ChatService_UpdateSection_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": "chat_v1_generated_chat_service_update_section_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.apps.chat_v1.ChatServiceClient", + "shortName": "ChatServiceClient" + }, + "fullName": "google.apps.chat_v1.ChatServiceClient.update_section", + "method": { + "fullName": "google.chat.v1.ChatService.UpdateSection", + "service": { + "fullName": "google.chat.v1.ChatService", + "shortName": "ChatService" + }, + "shortName": "UpdateSection" + }, + "parameters": [ + { + "name": "request", + "type": "google.apps.chat_v1.types.UpdateSectionRequest" + }, + { + "name": "section", + "type": "google.apps.chat_v1.types.Section" + }, + { + "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.apps.chat_v1.types.Section", + "shortName": "update_section" + }, + "description": "Sample for UpdateSection", + "file": "chat_v1_generated_chat_service_update_section_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "chat_v1_generated_ChatService_UpdateSection_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": "chat_v1_generated_chat_service_update_section_sync.py" + }, { "canonical": true, "clientMethod": { 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 7fc63f420f9b..95ed14043d74 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 @@ -82,6 +82,7 @@ membership, message, reaction, + section, slash_command, space, space_event, @@ -95,6 +96,7 @@ from google.apps.chat_v1.types import membership as gc_membership from google.apps.chat_v1.types import message as gc_message from google.apps.chat_v1.types import reaction as gc_reaction +from google.apps.chat_v1.types import section as gc_section from google.apps.chat_v1.types import space as gc_space from google.apps.chat_v1.types import ( space_notification_setting as gc_space_notification_setting, @@ -1308,9 +1310,11 @@ def test_chat_service_client_create_channel_credentials_file( "https://www.googleapis.com/auth/chat.admin.spaces.readonly", "https://www.googleapis.com/auth/chat.app.delete", "https://www.googleapis.com/auth/chat.app.memberships", + "https://www.googleapis.com/auth/chat.app.memberships.readonly", "https://www.googleapis.com/auth/chat.app.messages.readonly", "https://www.googleapis.com/auth/chat.app.spaces", "https://www.googleapis.com/auth/chat.app.spaces.create", + "https://www.googleapis.com/auth/chat.app.spaces.readonly", "https://www.googleapis.com/auth/chat.bot", "https://www.googleapis.com/auth/chat.customemojis", "https://www.googleapis.com/auth/chat.customemojis.readonly", @@ -1330,6 +1334,8 @@ def test_chat_service_client_create_channel_credentials_file( "https://www.googleapis.com/auth/chat.spaces.readonly", "https://www.googleapis.com/auth/chat.users.readstate", "https://www.googleapis.com/auth/chat.users.readstate.readonly", + "https://www.googleapis.com/auth/chat.users.sections", + "https://www.googleapis.com/auth/chat.users.sections.readonly", "https://www.googleapis.com/auth/chat.users.spacesettings", ), scopes=None, @@ -13769,13 +13775,83 @@ async def test_update_space_notification_setting_flattened_error_async(): ) -def test_create_message_rest_use_cached_wrapped_rpc(): +@pytest.mark.parametrize( + "request_type", + [ + gc_section.CreateSectionRequest, + dict, + ], +) +def test_create_section(request_type, transport: str = "grpc"): + client = ChatServiceClient( + 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_section), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = gc_section.Section( + name="name_value", + display_name="display_name_value", + sort_order=1091, + type_=gc_section.Section.SectionType.CUSTOM_SECTION, + ) + response = client.create_section(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = gc_section.CreateSectionRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gc_section.Section) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.sort_order == 1091 + assert response.type_ == gc_section.Section.SectionType.CUSTOM_SECTION + + +def test_create_section_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = ChatServiceClient( + 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 = gc_section.CreateSectionRequest( + parent="parent_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.create_section), "__call__") as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.create_section(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == gc_section.CreateSectionRequest( + parent="parent_value", + ) + + +def test_create_section_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport="grpc", ) # Should wrap all calls on client creation @@ -13783,204 +13859,331 @@ def test_create_message_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.create_message in client._transport._wrapped_methods + assert client._transport.create_section in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = 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_message] = mock_rpc - + client._transport._wrapped_methods[client._transport.create_section] = mock_rpc request = {} - client.create_message(request) + client.create_section(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.create_message(request) + client.create_section(request) # Establish 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_message_rest_required_fields( - request_type=gc_message.CreateMessageRequest, +@pytest.mark.asyncio +async def test_create_section_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", ): - transport_class = transports.ChatServiceRestTransport - - 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 = ChatServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).create_message._get_unset_required_fields(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_section + 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.create_section + ] = mock_rpc - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).create_message._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set( - ( - "message_id", - "message_reply_option", - "request_id", - "thread_key", - ) - ) - jsonified_request.update(unset_fields) + request = {} + await client.create_section(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 mock_rpc.call_count == 1 - client = ChatServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request = request_type(**request_init) + await client.create_section(request) - # Designate an appropriate value for the returned response. - return_value = gc_message.Message() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, "request") as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, "transcode") as transcode: - # A uri without fields and an empty body will force 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 = gc_message.Message.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) +@pytest.mark.asyncio +async def test_create_section_async( + transport: str = "grpc_asyncio", request_type=gc_section.CreateSectionRequest +): + client = ChatServiceAsyncClient( + 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.create_message(request) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.create_section), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gc_section.Section( + name="name_value", + display_name="display_name_value", + sort_order=1091, + type_=gc_section.Section.SectionType.CUSTOM_SECTION, + ) + ) + response = await client.create_section(request) - expected_params = [("$alt", "json;enum-encoding=int")] - actual_params = req.call_args.kwargs["params"] - assert expected_params == actual_params + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = gc_section.CreateSectionRequest() + assert args[0] == request + # Establish that the response is the type that we expect. + assert isinstance(response, gc_section.Section) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.sort_order == 1091 + assert response.type_ == gc_section.Section.SectionType.CUSTOM_SECTION -def test_create_message_rest_unset_required_fields(): - transport = transports.ChatServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials - ) - unset_fields = transport.create_message._get_unset_required_fields({}) - assert set(unset_fields) == ( - set( - ( - "messageId", - "messageReplyOption", - "requestId", - "threadKey", - ) - ) - & set( - ( - "parent", - "message", - ) - ) - ) +@pytest.mark.asyncio +async def test_create_section_async_from_dict(): + await test_create_section_async(request_type=dict) -def test_create_message_rest_flattened(): +def test_create_section_field_headers(): client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", ) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), "request") as req: - # Designate an appropriate value for the returned response. - return_value = gc_message.Message() + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = gc_section.CreateSectionRequest() - # get arguments that satisfy an http rule for this method - sample_request = {"parent": "spaces/sample1"} + request.parent = "parent_value" - # get truthy value for each flattened field - mock_args = dict( - parent="parent_value", - message=gc_message.Message(name="name_value"), - message_id="message_id_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.create_section), "__call__") as call: + call.return_value = gc_section.Section() + client.create_section(request) - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = gc_message.Message.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._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.create_message(**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"] - # Establish that the underlying call was 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=spaces/*}/messages" % client.transport._host, args[1] - ) +@pytest.mark.asyncio +async def test_create_section_field_headers_async(): + client = ChatServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) -def test_create_message_rest_flattened_error(transport: str = "rest"): - client = ChatServiceClient( + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = gc_section.CreateSectionRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.create_section), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gc_section.Section()) + await client.create_section(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_section_flattened(): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.create_section), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = gc_section.Section() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_section( + parent="parent_value", + section=gc_section.Section(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].section + mock_val = gc_section.Section(name="name_value") + assert arg == mock_val + + +def test_create_section_flattened_error(): + client = ChatServiceClient( credentials=ga_credentials.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_message( - gc_message.CreateMessageRequest(), + client.create_section( + gc_section.CreateSectionRequest(), parent="parent_value", - message=gc_message.Message(name="name_value"), - message_id="message_id_value", + section=gc_section.Section(name="name_value"), ) -def test_list_messages_rest_use_cached_wrapped_rpc(): +@pytest.mark.asyncio +async def test_create_section_flattened_async(): + client = ChatServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.create_section), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = gc_section.Section() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gc_section.Section()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_section( + parent="parent_value", + section=gc_section.Section(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].section + mock_val = gc_section.Section(name="name_value") + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_create_section_flattened_error_async(): + client = ChatServiceAsyncClient( + 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_section( + gc_section.CreateSectionRequest(), + parent="parent_value", + section=gc_section.Section(name="name_value"), + ) + + +@pytest.mark.parametrize( + "request_type", + [ + section.DeleteSectionRequest, + dict, + ], +) +def test_delete_section(request_type, transport: str = "grpc"): + client = ChatServiceClient( + 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_section), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.delete_section(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = section.DeleteSectionRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_section_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = ChatServiceClient( + 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 = section.DeleteSectionRequest( + name="name_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_section), "__call__") as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.delete_section(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == section.DeleteSectionRequest( + name="name_value", + ) + + +def test_delete_section_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport="grpc", ) # Should wrap all calls on client creation @@ -13988,255 +14191,315 @@ def test_list_messages_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.list_messages in client._transport._wrapped_methods + assert client._transport.delete_section in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = 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_messages] = mock_rpc - + client._transport._wrapped_methods[client._transport.delete_section] = mock_rpc request = {} - client.list_messages(request) + client.delete_section(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.list_messages(request) + client.delete_section(request) # Establish 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_messages_rest_required_fields(request_type=message.ListMessagesRequest): - transport_class = transports.ChatServiceRestTransport +@pytest.mark.asyncio +async def test_delete_section_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 = ChatServiceAsyncClient( + 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_section + in client._client._transport._wrapped_methods + ) - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).list_messages._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.delete_section + ] = mock_rpc - # verify required fields with default values are now present + request = {} + await client.delete_section(request) - jsonified_request["parent"] = "parent_value" + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).list_messages._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set( - ( - "filter", - "order_by", - "page_size", - "page_token", - "show_deleted", - ) - ) - jsonified_request.update(unset_fields) + await client.delete_section(request) - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == "parent_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 = ChatServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + +@pytest.mark.asyncio +async def test_delete_section_async( + transport: str = "grpc_asyncio", request_type=section.DeleteSectionRequest +): + client = ChatServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, ) - request = request_type(**request_init) - # Designate an appropriate value for the returned response. - return_value = message.ListMessagesResponse() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, "request") as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, "transcode") as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - "uri": "v1/sample_method", - "method": "get", - "query_params": pb_request, - } - transcode.return_value = transcode_result + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() - response_value = Response() - response_value.status_code = 200 + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_section), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_section(request) - # Convert return value to protobuf type - return_value = message.ListMessagesResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = section.DeleteSectionRequest() + assert args[0] == request - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + # Establish that the response is the type that we expect. + assert response is None - response = client.list_messages(request) - expected_params = [("$alt", "json;enum-encoding=int")] - actual_params = req.call_args.kwargs["params"] - assert expected_params == actual_params +@pytest.mark.asyncio +async def test_delete_section_async_from_dict(): + await test_delete_section_async(request_type=dict) -def test_list_messages_rest_unset_required_fields(): - transport = transports.ChatServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials +def test_delete_section_field_headers(): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), ) - unset_fields = transport.list_messages._get_unset_required_fields({}) - assert set(unset_fields) == ( - set( - ( - "filter", - "orderBy", - "pageSize", - "pageToken", - "showDeleted", - ) - ) - & set(("parent",)) + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = section.DeleteSectionRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_section), "__call__") as call: + call.return_value = None + client.delete_section(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_section_field_headers_async(): + client = ChatServiceAsyncClient( + 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 = section.DeleteSectionRequest() + + request.name = "name_value" -def test_list_messages_rest_flattened(): + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_section), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_section(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_section_flattened(): client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", ) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), "request") as req: - # Designate an appropriate value for the returned response. - return_value = message.ListMessagesResponse() + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_section), "__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_section( + name="name_value", + ) - # get arguments that satisfy an http rule for this method - sample_request = {"parent": "spaces/sample1"} + # 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_delete_section_flattened_error(): + client = ChatServiceClient( + 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_section( + section.DeleteSectionRequest(), + 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 = message.ListMessagesResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = 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_messages(**mock_args) +@pytest.mark.asyncio +async def test_delete_section_flattened_async(): + client = ChatServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_section), "__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_section( + 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=spaces/*}/messages" % 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_messages_rest_flattened_error(transport: str = "rest"): - client = ChatServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, +@pytest.mark.asyncio +async def test_delete_section_flattened_error_async(): + client = ChatServiceAsyncClient( + 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_messages( - message.ListMessagesRequest(), - parent="parent_value", + await client.delete_section( + section.DeleteSectionRequest(), + name="name_value", ) -def test_list_messages_rest_pager(transport: str = "rest"): +@pytest.mark.parametrize( + "request_type", + [ + gc_section.UpdateSectionRequest, + dict, + ], +) +def test_update_section(request_type, transport: str = "grpc"): client = ChatServiceClient( 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 = ( - message.ListMessagesResponse( - messages=[ - message.Message(), - message.Message(), - message.Message(), - ], - next_page_token="abc", - ), - message.ListMessagesResponse( - messages=[], - next_page_token="def", - ), - message.ListMessagesResponse( - messages=[ - message.Message(), - ], - next_page_token="ghi", - ), - message.ListMessagesResponse( - messages=[ - message.Message(), - message.Message(), - ], - ), + # Everything is optional in proto3 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_section), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = gc_section.Section( + name="name_value", + display_name="display_name_value", + sort_order=1091, + type_=gc_section.Section.SectionType.CUSTOM_SECTION, ) - # Two responses for two calls - response = response + response + response = client.update_section(request) - # Wrap the values into proper Response objs - response = tuple(message.ListMessagesResponse.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 = gc_section.UpdateSectionRequest() + assert args[0] == request - sample_request = {"parent": "spaces/sample1"} + # Establish that the response is the type that we expect. + assert isinstance(response, gc_section.Section) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.sort_order == 1091 + assert response.type_ == gc_section.Section.SectionType.CUSTOM_SECTION - pager = client.list_messages(request=sample_request) - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, message.Message) for i in results) +def test_update_section_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) - pages = list(client.list_messages(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 = gc_section.UpdateSectionRequest() + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.update_section), "__call__") as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.update_section(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == gc_section.UpdateSectionRequest() -def test_list_memberships_rest_use_cached_wrapped_rpc(): + +def test_update_section_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport="grpc", ) # Should wrap all calls on client creation @@ -14244,263 +14507,336 @@ def test_list_memberships_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.list_memberships in client._transport._wrapped_methods + assert client._transport.update_section in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = 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_memberships] = ( - mock_rpc - ) - + client._transport._wrapped_methods[client._transport.update_section] = mock_rpc request = {} - client.list_memberships(request) + client.update_section(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.list_memberships(request) + client.update_section(request) # Establish 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_memberships_rest_required_fields( - request_type=membership.ListMembershipsRequest, +@pytest.mark.asyncio +async def test_update_section_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", ): - transport_class = transports.ChatServiceRestTransport + # Clients should use _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 = ChatServiceAsyncClient( + 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.update_section + in client._client._transport._wrapped_methods + ) - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).list_memberships._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.update_section + ] = mock_rpc - # verify required fields with default values are now present + request = {} + await client.update_section(request) - jsonified_request["parent"] = "parent_value" + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).list_memberships._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set( - ( - "filter", - "page_size", - "page_token", - "show_groups", - "show_invited", - "use_admin_access", - ) + await client.update_section(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_section_async( + transport: str = "grpc_asyncio", request_type=gc_section.UpdateSectionRequest +): + client = ChatServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, ) - jsonified_request.update(unset_fields) - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == "parent_value" + # Everything is optional in proto3 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_section), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gc_section.Section( + name="name_value", + display_name="display_name_value", + sort_order=1091, + type_=gc_section.Section.SectionType.CUSTOM_SECTION, + ) + ) + response = await client.update_section(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = gc_section.UpdateSectionRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gc_section.Section) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.sort_order == 1091 + assert response.type_ == gc_section.Section.SectionType.CUSTOM_SECTION + +@pytest.mark.asyncio +async def test_update_section_async_from_dict(): + await test_update_section_async(request_type=dict) + + +def test_update_section_field_headers(): client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", ) - request = request_type(**request_init) - # Designate an appropriate value for the returned response. - return_value = membership.ListMembershipsResponse() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, "request") as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, "transcode") as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_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 = gc_section.UpdateSectionRequest() - response_value = Response() - response_value.status_code = 200 + request.section.name = "name_value" - # Convert return value to protobuf type - return_value = membership.ListMembershipsResponse.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_section), "__call__") as call: + call.return_value = gc_section.Section() + client.update_section(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_memberships(request) + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "section.name=name_value", + ) in kw["metadata"] - expected_params = [("$alt", "json;enum-encoding=int")] - actual_params = req.call_args.kwargs["params"] - assert expected_params == actual_params +@pytest.mark.asyncio +async def test_update_section_field_headers_async(): + client = ChatServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) -def test_list_memberships_rest_unset_required_fields(): - transport = transports.ChatServiceRestTransport( - 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 = gc_section.UpdateSectionRequest() + + request.section.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.update_section), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gc_section.Section()) + await client.update_section(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", + "section.name=name_value", + ) in kw["metadata"] + + +def test_update_section_flattened(): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), ) - unset_fields = transport.list_memberships._get_unset_required_fields({}) - assert set(unset_fields) == ( - set( - ( - "filter", - "pageSize", - "pageToken", - "showGroups", - "showInvited", - "useAdminAccess", - ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.update_section), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = gc_section.Section() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_section( + section=gc_section.Section(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) - & set(("parent",)) - ) + + # 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].section + mock_val = gc_section.Section(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_list_memberships_rest_flattened(): +def test_update_section_flattened_error(): client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", ) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), "request") as req: - # Designate an appropriate value for the returned response. - return_value = membership.ListMembershipsResponse() + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.update_section( + gc_section.UpdateSectionRequest(), + section=gc_section.Section(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) - # get arguments that satisfy an http rule for this method - sample_request = {"parent": "spaces/sample1"} - # get truthy value for each flattened field - mock_args = dict( - parent="parent_value", - ) - mock_args.update(sample_request) +@pytest.mark.asyncio +async def test_update_section_flattened_async(): + client = ChatServiceAsyncClient( + 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 = membership.ListMembershipsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._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_section), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = gc_section.Section() - client.list_memberships(**mock_args) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gc_section.Section()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_section( + section=gc_section.Section(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/{parent=spaces/*}/members" % client.transport._host, args[1] - ) + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].section + mock_val = gc_section.Section(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_list_memberships_rest_flattened_error(transport: str = "rest"): - client = ChatServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, +@pytest.mark.asyncio +async def test_update_section_flattened_error_async(): + client = ChatServiceAsyncClient( + 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_memberships( - membership.ListMembershipsRequest(), - parent="parent_value", + await client.update_section( + gc_section.UpdateSectionRequest(), + section=gc_section.Section(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) -def test_list_memberships_rest_pager(transport: str = "rest"): +@pytest.mark.parametrize( + "request_type", + [ + section.ListSectionsRequest, + dict, + ], +) +def test_list_sections(request_type, transport: str = "grpc"): client = ChatServiceClient( 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 = ( - membership.ListMembershipsResponse( - memberships=[ - membership.Membership(), - membership.Membership(), - membership.Membership(), - ], - next_page_token="abc", - ), - membership.ListMembershipsResponse( - memberships=[], - next_page_token="def", - ), - membership.ListMembershipsResponse( - memberships=[ - membership.Membership(), - ], - next_page_token="ghi", - ), - membership.ListMembershipsResponse( - memberships=[ - membership.Membership(), - membership.Membership(), - ], - ), - ) - # 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( - membership.ListMembershipsResponse.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_sections), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = section.ListSectionsResponse( + next_page_token="next_page_token_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_sections(request) - sample_request = {"parent": "spaces/sample1"} + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = section.ListSectionsRequest() + assert args[0] == request - pager = client.list_memberships(request=sample_request) + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListSectionsPager) + assert response.next_page_token == "next_page_token_value" - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, membership.Membership) for i in results) - pages = list(client.list_memberships(request=sample_request).pages) - for page_, token in zip(pages, ["abc", "def", "ghi", ""]): - assert page_.raw_page.next_page_token == token +def test_list_sections_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = ChatServiceClient( + 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 = section.ListSectionsRequest( + 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_sections), "__call__") as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.list_sections(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == section.ListSectionsRequest( + parent="parent_value", + page_token="page_token_value", + ) -def test_get_membership_rest_use_cached_wrapped_rpc(): +def test_list_sections_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport="grpc", ) # Should wrap all calls on client creation @@ -14508,351 +14844,513 @@ def test_get_membership_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.get_membership in client._transport._wrapped_methods + assert client._transport.list_sections in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = 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_membership] = mock_rpc - + client._transport._wrapped_methods[client._transport.list_sections] = mock_rpc request = {} - client.get_membership(request) + client.list_sections(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.get_membership(request) + client.list_sections(request) # Establish 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_membership_rest_required_fields( - request_type=membership.GetMembershipRequest, +@pytest.mark.asyncio +async def test_list_sections_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", ): - transport_class = transports.ChatServiceRestTransport + # Clients should use _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 = ChatServiceAsyncClient( + 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_sections + in client._client._transport._wrapped_methods + ) - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).get_membership._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.list_sections + ] = mock_rpc - # verify required fields with default values are now present + request = {} + await client.list_sections(request) - jsonified_request["name"] = "name_value" + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).get_membership._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("use_admin_access",)) - jsonified_request.update(unset_fields) + await client.list_sections(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 = ChatServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + +@pytest.mark.asyncio +async def test_list_sections_async( + transport: str = "grpc_asyncio", request_type=section.ListSectionsRequest +): + client = ChatServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, ) - request = request_type(**request_init) - # Designate an appropriate value for the returned response. - return_value = membership.Membership() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, "request") as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, "transcode") as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - "uri": "v1/sample_method", - "method": "get", - "query_params": pb_request, - } - transcode.return_value = transcode_result + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() - response_value = Response() - response_value.status_code = 200 + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_sections), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + section.ListSectionsResponse( + next_page_token="next_page_token_value", + ) + ) + response = await client.list_sections(request) - # Convert return value to protobuf type - return_value = membership.Membership.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = section.ListSectionsRequest() + assert args[0] == request - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListSectionsAsyncPager) + assert response.next_page_token == "next_page_token_value" - response = client.get_membership(request) - expected_params = [("$alt", "json;enum-encoding=int")] - actual_params = req.call_args.kwargs["params"] - assert expected_params == actual_params +@pytest.mark.asyncio +async def test_list_sections_async_from_dict(): + await test_list_sections_async(request_type=dict) -def test_get_membership_rest_unset_required_fields(): - transport = transports.ChatServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials +def test_list_sections_field_headers(): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), ) - unset_fields = transport.get_membership._get_unset_required_fields({}) - assert set(unset_fields) == (set(("useAdminAccess",)) & set(("name",))) + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = section.ListSectionsRequest() + request.parent = "parent_value" -def test_get_membership_rest_flattened(): - client = ChatServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_sections), "__call__") as call: + call.return_value = section.ListSectionsResponse() + client.list_sections(request) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), "request") as req: - # Designate an appropriate value for the returned response. - return_value = membership.Membership() + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request - # get arguments that satisfy an http rule for this method - sample_request = {"name": "spaces/sample1/members/sample2"} + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] - # 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 = membership.Membership.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._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_sections_field_headers_async(): + client = ChatServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) - client.get_membership(**mock_args) + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = section.ListSectionsRequest() - # Establish that the underlying call was 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=spaces/*/members/*}" % client.transport._host, args[1] + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_sections), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + section.ListSectionsResponse() ) + await client.list_sections(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request -def test_get_membership_rest_flattened_error(transport: str = "rest"): + # 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_sections_flattened(): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_sections), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = section.ListSectionsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_sections( + 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_sections_flattened_error(): client = ChatServiceClient( credentials=ga_credentials.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_membership( - membership.GetMembershipRequest(), - name="name_value", + client.list_sections( + section.ListSectionsRequest(), + parent="parent_value", ) -def test_get_message_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = ChatServiceClient( - 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_sections_flattened_async(): + client = ChatServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) - # Ensure method has been cached - assert client._transport.get_message 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_sections), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = section.ListSectionsResponse() - # Replace cached 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( + section.ListSectionsResponse() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_sections( + parent="parent_value", ) - client._transport._wrapped_methods[client._transport.get_message] = mock_rpc - - request = {} - client.get_message(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 - client.get_message(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_sections_flattened_error_async(): + client = ChatServiceAsyncClient( + 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_sections( + section.ListSectionsRequest(), + parent="parent_value", + ) -def test_get_message_rest_required_fields(request_type=message.GetMessageRequest): - transport_class = transports.ChatServiceRestTransport - 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_sections_pager(transport_name: str = "grpc"): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, ) - # verify fields with default values are dropped - - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).get_message._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_sections), "__call__") as call: + # Set the response to a series of pages. + call.side_effect = ( + section.ListSectionsResponse( + sections=[ + section.Section(), + section.Section(), + section.Section(), + ], + next_page_token="abc", + ), + section.ListSectionsResponse( + sections=[], + next_page_token="def", + ), + section.ListSectionsResponse( + sections=[ + section.Section(), + ], + next_page_token="ghi", + ), + section.ListSectionsResponse( + sections=[ + section.Section(), + section.Section(), + ], + ), + RuntimeError, + ) - # verify required fields with default values are now present + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)), + ) + pager = client.list_sections(request={}, retry=retry, timeout=timeout) - jsonified_request["name"] = "name_value" + assert pager._metadata == expected_metadata + assert pager._retry == retry + assert pager._timeout == timeout - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).get_message._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, section.Section) 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_sections_pages(transport_name: str = "grpc"): client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport=transport_name, ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = message.Message() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, "request") as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, "transcode") as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_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_sections), "__call__") as call: + # Set the response to a series of pages. + call.side_effect = ( + section.ListSectionsResponse( + sections=[ + section.Section(), + section.Section(), + section.Section(), + ], + next_page_token="abc", + ), + section.ListSectionsResponse( + sections=[], + next_page_token="def", + ), + section.ListSectionsResponse( + sections=[ + section.Section(), + ], + next_page_token="ghi", + ), + section.ListSectionsResponse( + sections=[ + section.Section(), + section.Section(), + ], + ), + RuntimeError, + ) + pages = list(client.list_sections(request={}).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token - # Convert return value to protobuf type - return_value = message.Message.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._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_sections_async_pager(): + client = ChatServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) - response = client.get_message(request) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_sections), "__call__", new_callable=mock.AsyncMock + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + section.ListSectionsResponse( + sections=[ + section.Section(), + section.Section(), + section.Section(), + ], + next_page_token="abc", + ), + section.ListSectionsResponse( + sections=[], + next_page_token="def", + ), + section.ListSectionsResponse( + sections=[ + section.Section(), + ], + next_page_token="ghi", + ), + section.ListSectionsResponse( + sections=[ + section.Section(), + section.Section(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_sections( + request={}, + ) + assert async_pager.next_page_token == "abc" + responses = [] + async for response in async_pager: # pragma: no branch + responses.append(response) - expected_params = [("$alt", "json;enum-encoding=int")] - actual_params = req.call_args.kwargs["params"] - assert expected_params == actual_params + assert len(responses) == 6 + assert all(isinstance(i, section.Section) for i in responses) -def test_get_message_rest_unset_required_fields(): - transport = transports.ChatServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials +@pytest.mark.asyncio +async def test_list_sections_async_pages(): + client = ChatServiceAsyncClient( + credentials=async_anonymous_credentials(), ) - unset_fields = transport.get_message._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name",))) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_sections), "__call__", new_callable=mock.AsyncMock + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + section.ListSectionsResponse( + sections=[ + section.Section(), + section.Section(), + section.Section(), + ], + next_page_token="abc", + ), + section.ListSectionsResponse( + sections=[], + next_page_token="def", + ), + section.ListSectionsResponse( + sections=[ + section.Section(), + ], + next_page_token="ghi", + ), + section.ListSectionsResponse( + sections=[ + section.Section(), + section.Section(), + ], + ), + RuntimeError, + ) + pages = [] + # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` + # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 + async for page_ in ( # pragma: no branch + await client.list_sections(request={}) + ).pages: + pages.append(page_) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token -def test_get_message_rest_flattened(): +@pytest.mark.parametrize( + "request_type", + [ + section.PositionSectionRequest, + dict, + ], +) +def test_position_section(request_type, transport: str = "grpc"): client = ChatServiceClient( 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 = message.Message() - - # get arguments that satisfy an http rule for this method - sample_request = {"name": "spaces/sample1/messages/sample2"} - - # get truthy value for each flattened field - mock_args = dict( - name="name_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 = message.Message.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._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.position_section), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = section.PositionSectionResponse() + response = client.position_section(request) - client.get_message(**mock_args) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = section.PositionSectionRequest() + 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=spaces/*/messages/*}" % client.transport._host, args[1] - ) + # Establish that the response is the type that we expect. + assert isinstance(response, section.PositionSectionResponse) -def test_get_message_rest_flattened_error(transport: str = "rest"): +def test_position_section_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. client = ChatServiceClient( 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_message( - message.GetMessageRequest(), + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = section.PositionSectionRequest( + name="name_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.position_section), "__call__") as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.position_section(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == section.PositionSectionRequest( name="name_value", ) -def test_update_message_rest_use_cached_wrapped_rpc(): +def test_position_section_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport="grpc", ) # Should wrap all calls on client creation @@ -14860,364 +15358,247 @@ def test_update_message_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.update_message in client._transport._wrapped_methods + assert client._transport.position_section in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = 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_message] = mock_rpc - + client._transport._wrapped_methods[client._transport.position_section] = ( + mock_rpc + ) request = {} - client.update_message(request) + client.position_section(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.update_message(request) + client.position_section(request) # Establish 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_message_rest_required_fields( - request_type=gc_message.UpdateMessageRequest, +@pytest.mark.asyncio +async def test_position_section_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", ): - transport_class = transports.ChatServiceRestTransport - - 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) - ) + # Clients should use _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 = ChatServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) - # verify fields with default values are dropped + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).update_message._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) + # Ensure method has been cached + assert ( + client._client._transport.position_section + 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.position_section + ] = mock_rpc - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).update_message._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set( - ( - "allow_missing", - "update_mask", - ) - ) - jsonified_request.update(unset_fields) + request = {} + await client.position_section(request) - # verify required fields with non-default values are left alone + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 - client = ChatServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request = request_type(**request_init) + await client.position_section(request) - # Designate an appropriate value for the returned response. - return_value = gc_message.Message() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, "request") as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, "transcode") as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - "uri": "v1/sample_method", - "method": "put", - "query_params": pb_request, - } - transcode_result["body"] = pb_request - transcode.return_value = transcode_result + # 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 = gc_message.Message.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) +@pytest.mark.asyncio +async def test_position_section_async( + transport: str = "grpc_asyncio", request_type=section.PositionSectionRequest +): + client = ChatServiceAsyncClient( + 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.update_message(request) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.position_section), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + section.PositionSectionResponse() + ) + response = await client.position_section(request) - expected_params = [("$alt", "json;enum-encoding=int")] - actual_params = req.call_args.kwargs["params"] - assert expected_params == actual_params + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = section.PositionSectionRequest() + assert args[0] == request + # Establish that the response is the type that we expect. + assert isinstance(response, section.PositionSectionResponse) -def test_update_message_rest_unset_required_fields(): - transport = transports.ChatServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials - ) - unset_fields = transport.update_message._get_unset_required_fields({}) - assert set(unset_fields) == ( - set( - ( - "allowMissing", - "updateMask", - ) - ) - & set( - ( - "message", - "updateMask", - ) - ) - ) +@pytest.mark.asyncio +async def test_position_section_async_from_dict(): + await test_position_section_async(request_type=dict) -def test_update_message_rest_flattened(): +def test_position_section_field_headers(): client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", ) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), "request") as req: - # Designate an appropriate value for the returned response. - return_value = gc_message.Message() - - # get arguments that satisfy an http rule for this method - sample_request = {"message": {"name": "spaces/sample1/messages/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 = section.PositionSectionRequest() - # get truthy value for each flattened field - mock_args = dict( - message=gc_message.Message(name="name_value"), - update_mask=field_mask_pb2.FieldMask(paths=["paths_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 = gc_message.Message.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._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.position_section), "__call__") as call: + call.return_value = section.PositionSectionResponse() + client.position_section(request) - client.update_message(**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/{message.name=spaces/*/messages/*}" % 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_update_message_rest_flattened_error(transport: str = "rest"): - client = ChatServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, +@pytest.mark.asyncio +async def test_position_section_field_headers_async(): + client = ChatServiceAsyncClient( + 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.update_message( - gc_message.UpdateMessageRequest(), - message=gc_message.Message(name="name_value"), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), - ) - - -def test_delete_message_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = ChatServiceClient( - 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 = section.PositionSectionRequest() - # Ensure method has been cached - assert client._transport.delete_message in client._transport._wrapped_methods + request.name = "name_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.position_section), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + section.PositionSectionResponse() ) - client._transport._wrapped_methods[client._transport.delete_message] = mock_rpc - - request = {} - client.delete_message(request) + await client.position_section(request) # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.delete_message(request) - - # Establish 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_message_rest_required_fields(request_type=message.DeleteMessageRequest): - transport_class = transports.ChatServiceRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads( - json_format.MessageToJson(pb_request, use_integers_for_enums=False) - ) - - # verify fields with default values are dropped - - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).delete_message._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["name"] = "name_value" + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).delete_message._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("force",)) - jsonified_request.update(unset_fields) + # 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 "name" in jsonified_request - assert jsonified_request["name"] == "name_value" +@pytest.mark.parametrize( + "request_type", + [ + section.ListSectionItemsRequest, + dict, + ], +) +def test_list_section_items(request_type, transport: str = "grpc"): client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport=transport, ) - 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_message(request) - - expected_params = [("$alt", "json;enum-encoding=int")] - actual_params = req.call_args.kwargs["params"] - assert expected_params == actual_params + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_section_items), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = section.ListSectionItemsResponse( + next_page_token="next_page_token_value", + ) + response = client.list_section_items(request) -def test_delete_message_rest_unset_required_fields(): - transport = transports.ChatServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials - ) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = section.ListSectionItemsRequest() + assert args[0] == request - unset_fields = transport.delete_message._get_unset_required_fields({}) - assert set(unset_fields) == (set(("force",)) & set(("name",))) + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListSectionItemsPager) + assert response.next_page_token == "next_page_token_value" -def test_delete_message_rest_flattened(): +def test_list_section_items_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. client = ChatServiceClient( 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 = None - - # get arguments that satisfy an http rule for this method - sample_request = {"name": "spaces/sample1/messages/sample2"} - - # 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_message(**mock_args) - - # Establish that the underlying call was 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=spaces/*/messages/*}" % client.transport._host, args[1] - ) - - -def test_delete_message_rest_flattened_error(transport: str = "rest"): - client = ChatServiceClient( - 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 = section.ListSectionItemsRequest( + parent="parent_value", + page_token="page_token_value", + filter="filter_value", ) - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.delete_message( - message.DeleteMessageRequest(), - name="name_value", + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_section_items), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.list_section_items(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == section.ListSectionItemsRequest( + parent="parent_value", + page_token="page_token_value", + filter="filter_value", ) -def test_get_attachment_rest_use_cached_wrapped_rpc(): +def test_list_section_items_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport="grpc", ) # Should wrap all calls on client creation @@ -15225,311 +15606,541 @@ def test_get_attachment_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.get_attachment in client._transport._wrapped_methods + assert ( + client._transport.list_section_items in client._transport._wrapped_methods + ) # Replace cached wrapped function with mock mock_rpc = 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_attachment] = mock_rpc - + client._transport._wrapped_methods[client._transport.list_section_items] = ( + mock_rpc + ) request = {} - client.get_attachment(request) + client.list_section_items(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.get_attachment(request) + client.list_section_items(request) # Establish 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_attachment_rest_required_fields( - request_type=attachment.GetAttachmentRequest, +@pytest.mark.asyncio +async def test_list_section_items_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", ): - transport_class = transports.ChatServiceRestTransport + # Clients should use _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 = ChatServiceAsyncClient( + 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_section_items + in client._client._transport._wrapped_methods + ) - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).get_attachment._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.list_section_items + ] = mock_rpc - # verify required fields with default values are now present + request = {} + await client.list_section_items(request) - jsonified_request["name"] = "name_value" + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).get_attachment._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) + await client.list_section_items(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 = ChatServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + +@pytest.mark.asyncio +async def test_list_section_items_async( + transport: str = "grpc_asyncio", request_type=section.ListSectionItemsRequest +): + client = ChatServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, ) - request = request_type(**request_init) - # Designate an appropriate value for the returned response. - return_value = attachment.Attachment() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, "request") as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, "transcode") as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - "uri": "v1/sample_method", - "method": "get", - "query_params": pb_request, - } - transcode.return_value = transcode_result + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() - response_value = Response() - response_value.status_code = 200 + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_section_items), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + section.ListSectionItemsResponse( + next_page_token="next_page_token_value", + ) + ) + response = await client.list_section_items(request) - # Convert return value to protobuf type - return_value = attachment.Attachment.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = section.ListSectionItemsRequest() + assert args[0] == request - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListSectionItemsAsyncPager) + assert response.next_page_token == "next_page_token_value" - response = client.get_attachment(request) - expected_params = [("$alt", "json;enum-encoding=int")] - actual_params = req.call_args.kwargs["params"] - assert expected_params == actual_params +@pytest.mark.asyncio +async def test_list_section_items_async_from_dict(): + await test_list_section_items_async(request_type=dict) -def test_get_attachment_rest_unset_required_fields(): - transport = transports.ChatServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials +def test_list_section_items_field_headers(): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), ) - unset_fields = transport.get_attachment._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name",))) + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = section.ListSectionItemsRequest() + request.parent = "parent_value" -def test_get_attachment_rest_flattened(): - client = ChatServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_section_items), "__call__" + ) as call: + call.return_value = section.ListSectionItemsResponse() + client.list_section_items(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_section_items_field_headers_async(): + client = ChatServiceAsyncClient( + 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 = attachment.Attachment() + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = section.ListSectionItemsRequest() - # get arguments that satisfy an http rule for this method - sample_request = {"name": "spaces/sample1/messages/sample2/attachments/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_section_items), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + section.ListSectionItemsResponse() ) - mock_args.update(sample_request) + await client.list_section_items(request) - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = attachment.Attachment.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._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_attachment(**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_section_items_flattened(): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_section_items), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = section.ListSectionItemsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_section_items( + 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=spaces/*/messages/*/attachments/*}" % 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_attachment_rest_flattened_error(transport: str = "rest"): +def test_list_section_items_flattened_error(): client = ChatServiceClient( credentials=ga_credentials.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_attachment( - attachment.GetAttachmentRequest(), - name="name_value", + client.list_section_items( + section.ListSectionItemsRequest(), + parent="parent_value", ) -def test_upload_attachment_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = ChatServiceClient( - 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_section_items_flattened_async(): + client = ChatServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) - # Ensure method has been cached - assert client._transport.upload_attachment 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_section_items), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = section.ListSectionItemsResponse() - # Replace cached 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( + section.ListSectionItemsResponse() ) - client._transport._wrapped_methods[client._transport.upload_attachment] = ( - mock_rpc + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_section_items( + parent="parent_value", ) - request = {} - client.upload_attachment(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.upload_attachment(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].parent + mock_val = "parent_value" + assert arg == mock_val -def test_upload_attachment_rest_required_fields( - request_type=attachment.UploadAttachmentRequest, -): - transport_class = transports.ChatServiceRestTransport - request_init = {} - request_init["parent"] = "" - request_init["filename"] = "" - request = 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_section_items_flattened_error_async(): + client = ChatServiceAsyncClient( + credentials=async_anonymous_credentials(), ) - # verify fields with default values are dropped - - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).upload_attachment._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_section_items( + section.ListSectionItemsRequest(), + parent="parent_value", + ) - # verify required fields with default values are now present - jsonified_request["parent"] = "parent_value" - jsonified_request["filename"] = "filename_value" +def test_list_section_items_pager(transport_name: str = "grpc"): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).upload_attachment._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_section_items), "__call__" + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + section.ListSectionItemsResponse( + section_items=[ + section.SectionItem(), + section.SectionItem(), + section.SectionItem(), + ], + next_page_token="abc", + ), + section.ListSectionItemsResponse( + section_items=[], + next_page_token="def", + ), + section.ListSectionItemsResponse( + section_items=[ + section.SectionItem(), + ], + next_page_token="ghi", + ), + section.ListSectionItemsResponse( + section_items=[ + section.SectionItem(), + section.SectionItem(), + ], + ), + RuntimeError, + ) - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == "parent_value" - assert "filename" in jsonified_request - assert jsonified_request["filename"] == "filename_value" + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)), + ) + pager = client.list_section_items(request={}, retry=retry, timeout=timeout) + + assert pager._metadata == expected_metadata + assert pager._retry == retry + assert pager._timeout == timeout + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, section.SectionItem) for i in results) + + +def test_list_section_items_pages(transport_name: str = "grpc"): client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport=transport_name, ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = attachment.UploadAttachmentResponse() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, "request") as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, "transcode") as transcode: - # A uri without fields and an empty body will force 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 + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_section_items), "__call__" + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + section.ListSectionItemsResponse( + section_items=[ + section.SectionItem(), + section.SectionItem(), + section.SectionItem(), + ], + next_page_token="abc", + ), + section.ListSectionItemsResponse( + section_items=[], + next_page_token="def", + ), + section.ListSectionItemsResponse( + section_items=[ + section.SectionItem(), + ], + next_page_token="ghi", + ), + section.ListSectionItemsResponse( + section_items=[ + section.SectionItem(), + section.SectionItem(), + ], + ), + RuntimeError, + ) + pages = list(client.list_section_items(request={}).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token - # Convert return value to protobuf type - return_value = attachment.UploadAttachmentResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._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_section_items_async_pager(): + client = ChatServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) - response = client.upload_attachment(request) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_section_items), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + section.ListSectionItemsResponse( + section_items=[ + section.SectionItem(), + section.SectionItem(), + section.SectionItem(), + ], + next_page_token="abc", + ), + section.ListSectionItemsResponse( + section_items=[], + next_page_token="def", + ), + section.ListSectionItemsResponse( + section_items=[ + section.SectionItem(), + ], + next_page_token="ghi", + ), + section.ListSectionItemsResponse( + section_items=[ + section.SectionItem(), + section.SectionItem(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_section_items( + request={}, + ) + assert async_pager.next_page_token == "abc" + responses = [] + async for response in async_pager: # pragma: no branch + responses.append(response) - expected_params = [("$alt", "json;enum-encoding=int")] - actual_params = req.call_args.kwargs["params"] - assert expected_params == actual_params + assert len(responses) == 6 + assert all(isinstance(i, section.SectionItem) for i in responses) -def test_upload_attachment_rest_unset_required_fields(): - transport = transports.ChatServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials +@pytest.mark.asyncio +async def test_list_section_items_async_pages(): + client = ChatServiceAsyncClient( + credentials=async_anonymous_credentials(), ) - unset_fields = transport.upload_attachment._get_unset_required_fields({}) - assert set(unset_fields) == ( - set(()) - & set( - ( - "parent", - "filename", - ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_section_items), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + section.ListSectionItemsResponse( + section_items=[ + section.SectionItem(), + section.SectionItem(), + section.SectionItem(), + ], + next_page_token="abc", + ), + section.ListSectionItemsResponse( + section_items=[], + next_page_token="def", + ), + section.ListSectionItemsResponse( + section_items=[ + section.SectionItem(), + ], + next_page_token="ghi", + ), + section.ListSectionItemsResponse( + section_items=[ + section.SectionItem(), + section.SectionItem(), + ], + ), + RuntimeError, ) + pages = [] + # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` + # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 + async for page_ in ( # pragma: no branch + await client.list_section_items(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", + [ + section.MoveSectionItemRequest, + dict, + ], +) +def test_move_section_item(request_type, transport: str = "grpc"): + client = ChatServiceClient( + 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_list_spaces_rest_use_cached_wrapped_rpc(): + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.move_section_item), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = section.MoveSectionItemResponse() + response = client.move_section_item(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = section.MoveSectionItemRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, section.MoveSectionItemResponse) + + +def test_move_section_item_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = ChatServiceClient( + 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 = section.MoveSectionItemRequest( + name="name_value", + target_section="target_section_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.move_section_item), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.move_section_item(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == section.MoveSectionItemRequest( + name="name_value", + target_section="target_section_value", + ) + + +def test_move_section_item_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport="grpc", ) # Should wrap all calls on client creation @@ -15537,90 +16148,271 @@ def test_list_spaces_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.list_spaces in client._transport._wrapped_methods + assert client._transport.move_section_item in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = 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_spaces] = mock_rpc - + client._transport._wrapped_methods[client._transport.move_section_item] = ( + mock_rpc + ) request = {} - client.list_spaces(request) + client.move_section_item(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.list_spaces(request) + client.move_section_item(request) # Establish 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_spaces_rest_pager(transport: str = "rest"): - client = ChatServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) +@pytest.mark.asyncio +async def test_move_section_item_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 = ChatServiceAsyncClient( + credentials=async_anonymous_credentials(), + 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 = ( - space.ListSpacesResponse( - spaces=[ - space.Space(), - space.Space(), - space.Space(), - ], - next_page_token="abc", - ), - space.ListSpacesResponse( - spaces=[], - next_page_token="def", - ), - space.ListSpacesResponse( - spaces=[ - space.Space(), - ], - next_page_token="ghi", - ), - space.ListSpacesResponse( - spaces=[ - space.Space(), - space.Space(), - ], - ), + # 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.move_section_item + in client._client._transport._wrapped_methods ) - # Two responses for two calls - response = response + response - # Wrap the values into proper Response objs - response = tuple(space.ListSpacesResponse.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 + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.move_section_item + ] = mock_rpc - sample_request = {} + request = {} + await client.move_section_item(request) - pager = client.list_spaces(request=sample_request) + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, space.Space) for i in results) + await client.move_section_item(request) - pages = list(client.list_spaces(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_search_spaces_rest_use_cached_wrapped_rpc(): +@pytest.mark.asyncio +async def test_move_section_item_async( + transport: str = "grpc_asyncio", request_type=section.MoveSectionItemRequest +): + client = ChatServiceAsyncClient( + 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.move_section_item), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + section.MoveSectionItemResponse() + ) + response = await client.move_section_item(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = section.MoveSectionItemRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, section.MoveSectionItemResponse) + + +@pytest.mark.asyncio +async def test_move_section_item_async_from_dict(): + await test_move_section_item_async(request_type=dict) + + +def test_move_section_item_field_headers(): + client = ChatServiceClient( + 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 = section.MoveSectionItemRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.move_section_item), "__call__" + ) as call: + call.return_value = section.MoveSectionItemResponse() + client.move_section_item(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_move_section_item_field_headers_async(): + client = ChatServiceAsyncClient( + 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 = section.MoveSectionItemRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.move_section_item), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + section.MoveSectionItemResponse() + ) + await client.move_section_item(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_move_section_item_flattened(): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.move_section_item), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = section.MoveSectionItemResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.move_section_item( + name="name_value", + target_section="target_section_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 + arg = args[0].target_section + mock_val = "target_section_value" + assert arg == mock_val + + +def test_move_section_item_flattened_error(): + client = ChatServiceClient( + 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.move_section_item( + section.MoveSectionItemRequest(), + name="name_value", + target_section="target_section_value", + ) + + +@pytest.mark.asyncio +async def test_move_section_item_flattened_async(): + client = ChatServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.move_section_item), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = section.MoveSectionItemResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + section.MoveSectionItemResponse() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.move_section_item( + name="name_value", + target_section="target_section_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 + arg = args[0].target_section + mock_val = "target_section_value" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_move_section_item_flattened_error_async(): + client = ChatServiceAsyncClient( + 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.move_section_item( + section.MoveSectionItemRequest(), + name="name_value", + target_section="target_section_value", + ) + + +def test_create_message_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -15634,33 +16426,35 @@ def test_search_spaces_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.search_spaces in client._transport._wrapped_methods + assert client._transport.create_message in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.Mock() mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.search_spaces] = mock_rpc + client._transport._wrapped_methods[client._transport.create_message] = mock_rpc request = {} - client.search_spaces(request) + client.create_message(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.search_spaces(request) + client.create_message(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_search_spaces_rest_required_fields(request_type=space.SearchSpacesRequest): +def test_create_message_rest_required_fields( + request_type=gc_message.CreateMessageRequest, +): transport_class = transports.ChatServiceRestTransport request_init = {} - request_init["query"] = "" + request_init["parent"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -15668,37 +16462,33 @@ def test_search_spaces_rest_required_fields(request_type=space.SearchSpacesReque ) # verify fields with default values are dropped - assert "query" not in jsonified_request unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).search_spaces._get_unset_required_fields(jsonified_request) + ).create_message._get_unset_required_fields(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["query"] = "query_value" + jsonified_request["parent"] = "parent_value" unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).search_spaces._get_unset_required_fields(jsonified_request) + ).create_message._get_unset_required_fields(jsonified_request) # Check that path parameters and body parameters are not mixing in. assert not set(unset_fields) - set( ( - "order_by", - "page_size", - "page_token", - "query", - "use_admin_access", + "message_id", + "message_reply_option", + "request_id", + "thread_key", ) ) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone - assert "query" in jsonified_request - assert jsonified_request["query"] == "query_value" + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -15707,7 +16497,7 @@ def test_search_spaces_rest_required_fields(request_type=space.SearchSpacesReque request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = space.SearchSpacesResponse() + return_value = gc_message.Message() # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values @@ -15719,117 +16509,115 @@ def test_search_spaces_rest_required_fields(request_type=space.SearchSpacesReque 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 = space.SearchSpacesResponse.pb(return_value) + return_value = gc_message.Message.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_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_spaces(request) + response = client.create_message(request) - expected_params = [ - ( - "query", - "", - ), - ("$alt", "json;enum-encoding=int"), - ] + expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_search_spaces_rest_unset_required_fields(): +def test_create_message_rest_unset_required_fields(): transport = transports.ChatServiceRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.search_spaces._get_unset_required_fields({}) + unset_fields = transport.create_message._get_unset_required_fields({}) assert set(unset_fields) == ( set( ( - "orderBy", - "pageSize", - "pageToken", - "query", - "useAdminAccess", + "messageId", + "messageReplyOption", + "requestId", + "threadKey", + ) + ) + & set( + ( + "parent", + "message", ) ) - & set(("query",)) ) -def test_search_spaces_rest_pager(transport: str = "rest"): +def test_create_message_rest_flattened(): client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport=transport, + transport="rest", ) # 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 = ( - space.SearchSpacesResponse( - spaces=[ - space.Space(), - space.Space(), - space.Space(), - ], - next_page_token="abc", - ), - space.SearchSpacesResponse( - spaces=[], - next_page_token="def", - ), - space.SearchSpacesResponse( - spaces=[ - space.Space(), - ], - next_page_token="ghi", - ), - space.SearchSpacesResponse( - spaces=[ - space.Space(), - space.Space(), - ], - ), + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = gc_message.Message() + + # get arguments that satisfy an http rule for this method + sample_request = {"parent": "spaces/sample1"} + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + message=gc_message.Message(name="name_value"), + message_id="message_id_value", ) - # Two responses for two calls - response = response + response + mock_args.update(sample_request) - # Wrap the values into proper Response objs - response = tuple(space.SearchSpacesResponse.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 + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = gc_message.Message.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - sample_request = {} + client.create_message(**mock_args) - pager = client.search_spaces(request=sample_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=spaces/*}/messages" % client.transport._host, args[1] + ) - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, space.Space) for i in results) - pages = list(client.search_spaces(request=sample_request).pages) - for page_, token in zip(pages, ["abc", "def", "ghi", ""]): - assert page_.raw_page.next_page_token == token +def test_create_message_rest_flattened_error(transport: str = "rest"): + client = ChatServiceClient( + credentials=ga_credentials.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_message( + gc_message.CreateMessageRequest(), + parent="parent_value", + message=gc_message.Message(name="name_value"), + message_id="message_id_value", + ) -def test_get_space_rest_use_cached_wrapped_rpc(): +def test_list_messages_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -15843,33 +16631,33 @@ def test_get_space_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.get_space in client._transport._wrapped_methods + assert client._transport.list_messages in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = 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_space] = mock_rpc + client._transport._wrapped_methods[client._transport.list_messages] = mock_rpc request = {} - client.get_space(request) + client.list_messages(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.get_space(request) + client.list_messages(request) # Establish 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_space_rest_required_fields(request_type=space.GetSpaceRequest): +def test_list_messages_rest_required_fields(request_type=message.ListMessagesRequest): transport_class = transports.ChatServiceRestTransport request_init = {} - request_init["name"] = "" + request_init["parent"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -15880,23 +16668,31 @@ def test_get_space_rest_required_fields(request_type=space.GetSpaceRequest): unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).get_space._get_unset_required_fields(jsonified_request) + ).list_messages._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present - jsonified_request["name"] = "name_value" + jsonified_request["parent"] = "parent_value" unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).get_space._get_unset_required_fields(jsonified_request) + ).list_messages._get_unset_required_fields(jsonified_request) # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("use_admin_access",)) + assert not set(unset_fields) - set( + ( + "filter", + "order_by", + "page_size", + "page_token", + "show_deleted", + ) + ) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == "name_value" + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -15905,7 +16701,7 @@ def test_get_space_rest_required_fields(request_type=space.GetSpaceRequest): request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = space.Space() + return_value = message.ListMessagesResponse() # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values @@ -15926,30 +16722,41 @@ def test_get_space_rest_required_fields(request_type=space.GetSpaceRequest): response_value.status_code = 200 # Convert return value to protobuf type - return_value = space.Space.pb(return_value) + return_value = message.ListMessagesResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_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_space(request) + response = client.list_messages(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_get_space_rest_unset_required_fields(): +def test_list_messages_rest_unset_required_fields(): transport = transports.ChatServiceRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.get_space._get_unset_required_fields({}) - assert set(unset_fields) == (set(("useAdminAccess",)) & set(("name",))) + unset_fields = transport.list_messages._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "filter", + "orderBy", + "pageSize", + "pageToken", + "showDeleted", + ) + ) + & set(("parent",)) + ) -def test_get_space_rest_flattened(): +def test_list_messages_rest_flattened(): client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -15958,14 +16765,14 @@ def test_get_space_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 = space.Space() + return_value = message.ListMessagesResponse() # get arguments that satisfy an http rule for this method - sample_request = {"name": "spaces/sample1"} + sample_request = {"parent": "spaces/sample1"} # get truthy value for each flattened field mock_args = dict( - name="name_value", + parent="parent_value", ) mock_args.update(sample_request) @@ -15973,24 +16780,24 @@ def test_get_space_rest_flattened(): response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = space.Space.pb(return_value) + return_value = message.ListMessagesResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = 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_space(**mock_args) + client.list_messages(**mock_args) # Establish that the underlying call was 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=spaces/*}" % client.transport._host, args[1] + "%s/v1/{parent=spaces/*}/messages" % client.transport._host, args[1] ) -def test_get_space_rest_flattened_error(transport: str = "rest"): +def test_list_messages_rest_flattened_error(transport: str = "rest"): client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -15999,52 +16806,118 @@ def test_get_space_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_space( - space.GetSpaceRequest(), - name="name_value", + client.list_messages( + message.ListMessagesRequest(), + parent="parent_value", ) -def test_create_space_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = ChatServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", +def test_list_messages_rest_pager(transport: str = "rest"): + client = ChatServiceClient( + 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 = ( + message.ListMessagesResponse( + messages=[ + message.Message(), + message.Message(), + message.Message(), + ], + next_page_token="abc", + ), + message.ListMessagesResponse( + messages=[], + next_page_token="def", + ), + message.ListMessagesResponse( + messages=[ + message.Message(), + ], + next_page_token="ghi", + ), + message.ListMessagesResponse( + messages=[ + message.Message(), + message.Message(), + ], + ), ) + # Two responses for two calls + response = response + response - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() + # Wrap the values into proper Response objs + response = tuple(message.ListMessagesResponse.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 - # Ensure method has been cached - assert client._transport.create_space in client._transport._wrapped_methods + sample_request = {"parent": "spaces/sample1"} - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = ( + pager = client.list_messages(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, message.Message) for i in results) + + pages = list(client.list_messages(request=sample_request).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +def test_list_memberships_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should 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_memberships in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_space] = mock_rpc + client._transport._wrapped_methods[client._transport.list_memberships] = ( + mock_rpc + ) request = {} - client.create_space(request) + client.list_memberships(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.create_space(request) + client.list_memberships(request) # Establish 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_space_rest_required_fields(request_type=gc_space.CreateSpaceRequest): +def test_list_memberships_rest_required_fields( + request_type=membership.ListMembershipsRequest, +): transport_class = transports.ChatServiceRestTransport request_init = {} + request_init["parent"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -16055,19 +16928,32 @@ def test_create_space_rest_required_fields(request_type=gc_space.CreateSpaceRequ unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).create_space._get_unset_required_fields(jsonified_request) + ).list_memberships._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present + jsonified_request["parent"] = "parent_value" + unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).create_space._get_unset_required_fields(jsonified_request) + ).list_memberships._get_unset_required_fields(jsonified_request) # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("request_id",)) + assert not set(unset_fields) - set( + ( + "filter", + "page_size", + "page_token", + "show_groups", + "show_invited", + "use_admin_access", + ) + ) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -16076,7 +16962,7 @@ def test_create_space_rest_required_fields(request_type=gc_space.CreateSpaceRequ request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = gc_space.Space() + return_value = membership.ListMembershipsResponse() # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values @@ -16088,40 +16974,51 @@ def test_create_space_rest_required_fields(request_type=gc_space.CreateSpaceRequ 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 = gc_space.Space.pb(return_value) + return_value = membership.ListMembershipsResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_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_space(request) + response = client.list_memberships(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_create_space_rest_unset_required_fields(): +def test_list_memberships_rest_unset_required_fields(): transport = transports.ChatServiceRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.create_space._get_unset_required_fields({}) - assert set(unset_fields) == (set(("requestId",)) & set(("space",))) + unset_fields = transport.list_memberships._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "filter", + "pageSize", + "pageToken", + "showGroups", + "showInvited", + "useAdminAccess", + ) + ) + & set(("parent",)) + ) -def test_create_space_rest_flattened(): +def test_list_memberships_rest_flattened(): client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -16130,14 +17027,14 @@ def test_create_space_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 = gc_space.Space() + return_value = membership.ListMembershipsResponse() # get arguments that satisfy an http rule for this method - sample_request = {} + sample_request = {"parent": "spaces/sample1"} # get truthy value for each flattened field mock_args = dict( - space=gc_space.Space(name="name_value"), + parent="parent_value", ) mock_args.update(sample_request) @@ -16145,22 +17042,24 @@ def test_create_space_rest_flattened(): response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = gc_space.Space.pb(return_value) + return_value = membership.ListMembershipsResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = 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_space(**mock_args) + client.list_memberships(**mock_args) # Establish that the underlying call was made with the expected # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1/spaces" % client.transport._host, args[1]) + assert path_template.validate( + "%s/v1/{parent=spaces/*}/members" % client.transport._host, args[1] + ) -def test_create_space_rest_flattened_error(transport: str = "rest"): +def test_list_memberships_rest_flattened_error(transport: str = "rest"): client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -16169,13 +17068,76 @@ def test_create_space_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_space( - gc_space.CreateSpaceRequest(), - space=gc_space.Space(name="name_value"), + client.list_memberships( + membership.ListMembershipsRequest(), + parent="parent_value", ) -def test_set_up_space_rest_use_cached_wrapped_rpc(): +def test_list_memberships_rest_pager(transport: str = "rest"): + client = ChatServiceClient( + 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 = ( + membership.ListMembershipsResponse( + memberships=[ + membership.Membership(), + membership.Membership(), + membership.Membership(), + ], + next_page_token="abc", + ), + membership.ListMembershipsResponse( + memberships=[], + next_page_token="def", + ), + membership.ListMembershipsResponse( + memberships=[ + membership.Membership(), + ], + next_page_token="ghi", + ), + membership.ListMembershipsResponse( + memberships=[ + membership.Membership(), + membership.Membership(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple( + membership.ListMembershipsResponse.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": "spaces/sample1"} + + pager = client.list_memberships(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, membership.Membership) for i in results) + + pages = list(client.list_memberships(request=sample_request).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +def test_get_membership_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -16189,32 +17151,35 @@ def test_set_up_space_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.set_up_space in client._transport._wrapped_methods + assert client._transport.get_membership in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = 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_space] = mock_rpc + client._transport._wrapped_methods[client._transport.get_membership] = mock_rpc request = {} - client.set_up_space(request) + client.get_membership(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.set_up_space(request) + client.get_membership(request) # Establish 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_space_rest_required_fields(request_type=space_setup.SetUpSpaceRequest): +def test_get_membership_rest_required_fields( + request_type=membership.GetMembershipRequest, +): transport_class = transports.ChatServiceRestTransport request_init = {} + request_init["name"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -16225,17 +17190,23 @@ def test_set_up_space_rest_required_fields(request_type=space_setup.SetUpSpaceRe unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).set_up_space._get_unset_required_fields(jsonified_request) + ).get_membership._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present + jsonified_request["name"] = "name_value" + unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).set_up_space._get_unset_required_fields(jsonified_request) + ).get_membership._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("use_admin_access",)) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -16244,7 +17215,7 @@ def test_set_up_space_rest_required_fields(request_type=space_setup.SetUpSpaceRe request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = space.Space() + return_value = membership.Membership() # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values @@ -16256,79 +17227,135 @@ def test_set_up_space_rest_required_fields(request_type=space_setup.SetUpSpaceRe 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 = space.Space.pb(return_value) + return_value = membership.Membership.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_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_space(request) + response = client.get_membership(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_set_up_space_rest_unset_required_fields(): +def test_get_membership_rest_unset_required_fields(): transport = transports.ChatServiceRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.set_up_space._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("space",))) + unset_fields = transport.get_membership._get_unset_required_fields({}) + assert set(unset_fields) == (set(("useAdminAccess",)) & set(("name",))) -def test_update_space_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = ChatServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) +def test_get_membership_rest_flattened(): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = membership.Membership() - # Ensure method has been cached - assert client._transport.update_space in client._transport._wrapped_methods + # get arguments that satisfy an http rule for this method + sample_request = {"name": "spaces/sample1/members/sample2"} - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. + # get truthy value for each flattened field + mock_args = dict( + name="name_value", ) - client._transport._wrapped_methods[client._transport.update_space] = mock_rpc - - request = {} - client.update_space(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 + mock_args.update(sample_request) - client.update_space(request) + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = membership.Membership.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = 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_membership(**mock_args) + + # Establish that the underlying call was 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=spaces/*/members/*}" % client.transport._host, args[1] + ) + + +def test_get_membership_rest_flattened_error(transport: str = "rest"): + client = ChatServiceClient( + credentials=ga_credentials.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_membership( + membership.GetMembershipRequest(), + name="name_value", + ) + + +def test_get_message_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should 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_message in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_message] = mock_rpc + + request = {} + client.get_message(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_message(request) # Establish 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_space_rest_required_fields(request_type=gc_space.UpdateSpaceRequest): +def test_get_message_rest_required_fields(request_type=message.GetMessageRequest): transport_class = transports.ChatServiceRestTransport request_init = {} + request_init["name"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -16339,24 +17366,21 @@ def test_update_space_rest_required_fields(request_type=gc_space.UpdateSpaceRequ unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).update_space._get_unset_required_fields(jsonified_request) + ).get_message._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present + jsonified_request["name"] = "name_value" + unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).update_space._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set( - ( - "update_mask", - "use_admin_access", - ) - ) + ).get_message._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -16365,7 +17389,7 @@ def test_update_space_rest_required_fields(request_type=gc_space.UpdateSpaceRequ request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = gc_space.Space() + return_value = message.Message() # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values @@ -16377,53 +17401,39 @@ def test_update_space_rest_required_fields(request_type=gc_space.UpdateSpaceRequ 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 = gc_space.Space.pb(return_value) + return_value = message.Message.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_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_space(request) + response = client.get_message(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_update_space_rest_unset_required_fields(): +def test_get_message_rest_unset_required_fields(): transport = transports.ChatServiceRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.update_space._get_unset_required_fields({}) - assert set(unset_fields) == ( - set( - ( - "updateMask", - "useAdminAccess", - ) - ) - & set( - ( - "space", - "updateMask", - ) - ) - ) + unset_fields = transport.get_message._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) -def test_update_space_rest_flattened(): +def test_get_message_rest_flattened(): client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -16432,15 +17442,14 @@ def test_update_space_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 = gc_space.Space() + return_value = message.Message() # get arguments that satisfy an http rule for this method - sample_request = {"space": {"name": "spaces/sample1"}} + sample_request = {"name": "spaces/sample1/messages/sample2"} # get truthy value for each flattened field mock_args = dict( - space=gc_space.Space(name="name_value"), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + name="name_value", ) mock_args.update(sample_request) @@ -16448,24 +17457,24 @@ def test_update_space_rest_flattened(): response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = gc_space.Space.pb(return_value) + return_value = message.Message.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = 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_space(**mock_args) + client.get_message(**mock_args) # Establish that the underlying call was made with the expected # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] assert path_template.validate( - "%s/v1/{space.name=spaces/*}" % client.transport._host, args[1] + "%s/v1/{name=spaces/*/messages/*}" % client.transport._host, args[1] ) -def test_update_space_rest_flattened_error(transport: str = "rest"): +def test_get_message_rest_flattened_error(transport: str = "rest"): client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -16474,14 +17483,13 @@ def test_update_space_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_space( - gc_space.UpdateSpaceRequest(), - space=gc_space.Space(name="name_value"), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + client.get_message( + message.GetMessageRequest(), + name="name_value", ) -def test_delete_space_rest_use_cached_wrapped_rpc(): +def test_update_message_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -16495,33 +17503,34 @@ def test_delete_space_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.delete_space in client._transport._wrapped_methods + assert client._transport.update_message in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = 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_space] = mock_rpc + client._transport._wrapped_methods[client._transport.update_message] = mock_rpc request = {} - client.delete_space(request) + client.update_message(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.delete_space(request) + client.update_message(request) # Establish 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_space_rest_required_fields(request_type=space.DeleteSpaceRequest): +def test_update_message_rest_required_fields( + request_type=gc_message.UpdateMessageRequest, +): transport_class = transports.ChatServiceRestTransport request_init = {} - request_init["name"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -16532,23 +17541,24 @@ def test_delete_space_rest_required_fields(request_type=space.DeleteSpaceRequest unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).delete_space._get_unset_required_fields(jsonified_request) + ).update_message._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present - jsonified_request["name"] = "name_value" - unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).delete_space._get_unset_required_fields(jsonified_request) + ).update_message._get_unset_required_fields(jsonified_request) # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("use_admin_access",)) + assert not set(unset_fields) - set( + ( + "allow_missing", + "update_mask", + ) + ) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == "name_value" client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -16557,7 +17567,7 @@ def test_delete_space_rest_required_fields(request_type=space.DeleteSpaceRequest request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = None + return_value = gc_message.Message() # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values @@ -16569,36 +17579,53 @@ def test_delete_space_rest_required_fields(request_type=space.DeleteSpaceRequest pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "delete", + "method": "put", "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 = "" + + # Convert return value to protobuf type + return_value = gc_message.Message.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) response_value._content = json_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_space(request) + response = client.update_message(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_delete_space_rest_unset_required_fields(): +def test_update_message_rest_unset_required_fields(): transport = transports.ChatServiceRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.delete_space._get_unset_required_fields({}) - assert set(unset_fields) == (set(("useAdminAccess",)) & set(("name",))) + unset_fields = transport.update_message._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "allowMissing", + "updateMask", + ) + ) + & set( + ( + "message", + "updateMask", + ) + ) + ) -def test_delete_space_rest_flattened(): +def test_update_message_rest_flattened(): client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -16607,37 +17634,40 @@ def test_delete_space_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 = None + return_value = gc_message.Message() # get arguments that satisfy an http rule for this method - sample_request = {"name": "spaces/sample1"} + sample_request = {"message": {"name": "spaces/sample1/messages/sample2"}} # get truthy value for each flattened field mock_args = dict( - name="name_value", + message=gc_message.Message(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 = "" + # Convert return value to protobuf type + return_value = gc_message.Message.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) response_value._content = 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_space(**mock_args) + client.update_message(**mock_args) # Establish that the underlying call was 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=spaces/*}" % client.transport._host, args[1] + "%s/v1/{message.name=spaces/*/messages/*}" % client.transport._host, args[1] ) -def test_delete_space_rest_flattened_error(transport: str = "rest"): +def test_update_message_rest_flattened_error(transport: str = "rest"): client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -16646,13 +17676,14 @@ def test_delete_space_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_space( - space.DeleteSpaceRequest(), - name="name_value", + client.update_message( + gc_message.UpdateMessageRequest(), + message=gc_message.Message(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) -def test_complete_import_space_rest_use_cached_wrapped_rpc(): +def test_delete_message_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -16666,36 +17697,29 @@ def test_complete_import_space_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert ( - client._transport.complete_import_space - in client._transport._wrapped_methods - ) + assert client._transport.delete_message in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.Mock() mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.complete_import_space] = ( - mock_rpc - ) + client._transport._wrapped_methods[client._transport.delete_message] = mock_rpc request = {} - client.complete_import_space(request) + client.delete_message(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.complete_import_space(request) + client.delete_message(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_complete_import_space_rest_required_fields( - request_type=space.CompleteImportSpaceRequest, -): +def test_delete_message_rest_required_fields(request_type=message.DeleteMessageRequest): transport_class = transports.ChatServiceRestTransport request_init = {} @@ -16710,7 +17734,7 @@ def test_complete_import_space_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).complete_import_space._get_unset_required_fields(jsonified_request) + ).delete_message._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present @@ -16719,7 +17743,9 @@ def test_complete_import_space_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).complete_import_space._get_unset_required_fields(jsonified_request) + ).delete_message._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("force",)) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone @@ -16733,7 +17759,7 @@ def test_complete_import_space_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = space.CompleteImportSpaceResponse() + 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 @@ -16745,40 +17771,90 @@ def test_complete_import_space_rest_required_fields( pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "post", + "method": "delete", "query_params": pb_request, } - transcode_result["body"] = pb_request transcode.return_value = transcode_result response_value = Response() response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = space.CompleteImportSpaceResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) + json_return_value = "" response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.complete_import_space(request) + response = client.delete_message(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_complete_import_space_rest_unset_required_fields(): +def test_delete_message_rest_unset_required_fields(): transport = transports.ChatServiceRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.complete_import_space._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name",))) + unset_fields = transport.delete_message._get_unset_required_fields({}) + assert set(unset_fields) == (set(("force",)) & set(("name",))) -def test_find_direct_message_rest_use_cached_wrapped_rpc(): +def test_delete_message_rest_flattened(): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and 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": "spaces/sample1/messages/sample2"} + + # 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_message(**mock_args) + + # Establish that the underlying call was 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=spaces/*/messages/*}" % client.transport._host, args[1] + ) + + +def test_delete_message_rest_flattened_error(transport: str = "rest"): + client = ChatServiceClient( + credentials=ga_credentials.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_message( + message.DeleteMessageRequest(), + name="name_value", + ) + + +def test_get_attachment_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -16792,34 +17868,30 @@ def test_find_direct_message_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert ( - client._transport.find_direct_message in client._transport._wrapped_methods - ) + assert client._transport.get_attachment in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.Mock() mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.find_direct_message] = ( - mock_rpc - ) + client._transport._wrapped_methods[client._transport.get_attachment] = mock_rpc request = {} - client.find_direct_message(request) + client.get_attachment(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.find_direct_message(request) + client.get_attachment(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_find_direct_message_rest_required_fields( - request_type=space.FindDirectMessageRequest, +def test_get_attachment_rest_required_fields( + request_type=attachment.GetAttachmentRequest, ): transport_class = transports.ChatServiceRestTransport @@ -16832,24 +17904,19 @@ def test_find_direct_message_rest_required_fields( ) # verify fields with default values are dropped - assert "name" not in jsonified_request unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).find_direct_message._get_unset_required_fields(jsonified_request) + ).get_attachment._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present - assert "name" in jsonified_request - assert jsonified_request["name"] == request_init["name"] jsonified_request["name"] = "name_value" unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).find_direct_message._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("name",)) + ).get_attachment._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone @@ -16863,7 +17930,7 @@ def test_find_direct_message_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = space.Space() + return_value = attachment.Attachment() # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values @@ -16884,36 +17951,87 @@ def test_find_direct_message_rest_required_fields( response_value.status_code = 200 # Convert return value to protobuf type - return_value = space.Space.pb(return_value) + return_value = attachment.Attachment.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.find_direct_message(request) + response = client.get_attachment(request) - expected_params = [ - ( - "name", - "", - ), - ("$alt", "json;enum-encoding=int"), - ] + expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_find_direct_message_rest_unset_required_fields(): +def test_get_attachment_rest_unset_required_fields(): transport = transports.ChatServiceRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.find_direct_message._get_unset_required_fields({}) - assert set(unset_fields) == (set(("name",)) & set(("name",))) + unset_fields = transport.get_attachment._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) -def test_create_membership_rest_use_cached_wrapped_rpc(): +def test_get_attachment_rest_flattened(): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = attachment.Attachment() + + # get arguments that satisfy an http rule for this method + sample_request = {"name": "spaces/sample1/messages/sample2/attachments/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 = attachment.Attachment.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = 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_attachment(**mock_args) + + # Establish that the underlying call was 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=spaces/*/messages/*/attachments/*}" % client.transport._host, + args[1], + ) + + +def test_get_attachment_rest_flattened_error(transport: str = "rest"): + client = ChatServiceClient( + credentials=ga_credentials.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_attachment( + attachment.GetAttachmentRequest(), + name="name_value", + ) + + +def test_upload_attachment_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -16927,37 +18045,38 @@ def test_create_membership_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.create_membership in client._transport._wrapped_methods + assert client._transport.upload_attachment in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = 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_membership] = ( + client._transport._wrapped_methods[client._transport.upload_attachment] = ( mock_rpc ) request = {} - client.create_membership(request) + client.upload_attachment(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.create_membership(request) + client.upload_attachment(request) # Establish 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_membership_rest_required_fields( - request_type=gc_membership.CreateMembershipRequest, +def test_upload_attachment_rest_required_fields( + request_type=attachment.UploadAttachmentRequest, ): transport_class = transports.ChatServiceRestTransport request_init = {} request_init["parent"] = "" + request_init["filename"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -16968,23 +18087,24 @@ def test_create_membership_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).create_membership._get_unset_required_fields(jsonified_request) + ).upload_attachment._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present jsonified_request["parent"] = "parent_value" + jsonified_request["filename"] = "filename_value" unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).create_membership._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("use_admin_access",)) + ).upload_attachment._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone assert "parent" in jsonified_request assert jsonified_request["parent"] == "parent_value" + assert "filename" in jsonified_request + assert jsonified_request["filename"] == "filename_value" client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -16993,7 +18113,7 @@ def test_create_membership_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = gc_membership.Membership() + return_value = attachment.UploadAttachmentResponse() # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values @@ -17015,96 +18135,135 @@ def test_create_membership_rest_required_fields( response_value.status_code = 200 # Convert return value to protobuf type - return_value = gc_membership.Membership.pb(return_value) + return_value = attachment.UploadAttachmentResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_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_membership(request) + response = client.upload_attachment(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_create_membership_rest_unset_required_fields(): +def test_upload_attachment_rest_unset_required_fields(): transport = transports.ChatServiceRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.create_membership._get_unset_required_fields({}) + unset_fields = transport.upload_attachment._get_unset_required_fields({}) assert set(unset_fields) == ( - set(("useAdminAccess",)) + set(()) & set( ( "parent", - "membership", + "filename", ) ) ) -def test_create_membership_rest_flattened(): - client = ChatServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) +def test_list_spaces_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), "request") as req: - # Designate an appropriate value for the returned response. - return_value = gc_membership.Membership() + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() - # get arguments that satisfy an http rule for this method - sample_request = {"parent": "spaces/sample1"} + # Ensure method has been cached + assert client._transport.list_spaces in client._transport._wrapped_methods - # get truthy value for each flattened field - mock_args = dict( - parent="parent_value", - membership=gc_membership.Membership(name="name_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_args.update(sample_request) + client._transport._wrapped_methods[client._transport.list_spaces] = mock_rpc - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = gc_membership.Membership.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._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 = {} + client.list_spaces(request) - client.create_membership(**mock_args) + # 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(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate( - "%s/v1/{parent=spaces/*}/members" % client.transport._host, args[1] - ) + client.list_spaces(request) + + # Establish 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_membership_rest_flattened_error(transport: str = "rest"): +def test_list_spaces_rest_pager(transport: str = "rest"): client = ChatServiceClient( credentials=ga_credentials.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_membership( - gc_membership.CreateMembershipRequest(), - parent="parent_value", - membership=gc_membership.Membership(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 = ( + space.ListSpacesResponse( + spaces=[ + space.Space(), + space.Space(), + space.Space(), + ], + next_page_token="abc", + ), + space.ListSpacesResponse( + spaces=[], + next_page_token="def", + ), + space.ListSpacesResponse( + spaces=[ + space.Space(), + ], + next_page_token="ghi", + ), + space.ListSpacesResponse( + spaces=[ + space.Space(), + space.Space(), + ], + ), ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(space.ListSpacesResponse.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 = {} + pager = client.list_spaces(request=sample_request) -def test_update_membership_rest_use_cached_wrapped_rpc(): + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, space.Space) for i in results) + + pages = list(client.list_spaces(request=sample_request).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +def test_search_spaces_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -17118,36 +18277,33 @@ def test_update_membership_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.update_membership in client._transport._wrapped_methods + assert client._transport.search_spaces in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = 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_membership] = ( - mock_rpc - ) + client._transport._wrapped_methods[client._transport.search_spaces] = mock_rpc request = {} - client.update_membership(request) + client.search_spaces(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.update_membership(request) + client.search_spaces(request) # Establish 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_membership_rest_required_fields( - request_type=gc_membership.UpdateMembershipRequest, -): +def test_search_spaces_rest_required_fields(request_type=space.SearchSpacesRequest): transport_class = transports.ChatServiceRestTransport request_init = {} + request_init["query"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -17155,27 +18311,37 @@ def test_update_membership_rest_required_fields( ) # verify fields with default values are dropped + assert "query" not in jsonified_request unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).update_membership._get_unset_required_fields(jsonified_request) + ).search_spaces._get_unset_required_fields(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["query"] = "query_value" unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).update_membership._get_unset_required_fields(jsonified_request) + ).search_spaces._get_unset_required_fields(jsonified_request) # Check that path parameters and body parameters are not mixing in. assert not set(unset_fields) - set( ( - "update_mask", + "order_by", + "page_size", + "page_token", + "query", "use_admin_access", ) ) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone + assert "query" in jsonified_request + assert jsonified_request["query"] == "query_value" client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -17184,7 +18350,7 @@ def test_update_membership_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = gc_membership.Membership() + return_value = space.SearchSpacesResponse() # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values @@ -17196,112 +18362,117 @@ def test_update_membership_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 = gc_membership.Membership.pb(return_value) + return_value = space.SearchSpacesResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_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_membership(request) + response = client.search_spaces(request) - expected_params = [("$alt", "json;enum-encoding=int")] + expected_params = [ + ( + "query", + "", + ), + ("$alt", "json;enum-encoding=int"), + ] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_update_membership_rest_unset_required_fields(): +def test_search_spaces_rest_unset_required_fields(): transport = transports.ChatServiceRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.update_membership._get_unset_required_fields({}) + unset_fields = transport.search_spaces._get_unset_required_fields({}) assert set(unset_fields) == ( set( ( - "updateMask", + "orderBy", + "pageSize", + "pageToken", + "query", "useAdminAccess", ) ) - & set( - ( - "membership", - "updateMask", - ) - ) + & set(("query",)) ) -def test_update_membership_rest_flattened(): +def test_search_spaces_rest_pager(transport: str = "rest"): client = ChatServiceClient( 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 = gc_membership.Membership() - - # get arguments that satisfy an http rule for this method - sample_request = {"membership": {"name": "spaces/sample1/members/sample2"}} - - # get truthy value for each flattened field - mock_args = dict( - membership=gc_membership.Membership(name="name_value"), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + 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 = ( + space.SearchSpacesResponse( + spaces=[ + space.Space(), + space.Space(), + space.Space(), + ], + next_page_token="abc", + ), + space.SearchSpacesResponse( + spaces=[], + next_page_token="def", + ), + space.SearchSpacesResponse( + spaces=[ + space.Space(), + ], + next_page_token="ghi", + ), + space.SearchSpacesResponse( + spaces=[ + space.Space(), + space.Space(), + ], + ), ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = gc_membership.Membership.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + # Two responses for two calls + response = response + response - client.update_membership(**mock_args) + # Wrap the values into proper Response objs + response = tuple(space.SearchSpacesResponse.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 call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate( - "%s/v1/{membership.name=spaces/*/members/*}" % client.transport._host, - args[1], - ) + sample_request = {} + pager = client.search_spaces(request=sample_request) -def test_update_membership_rest_flattened_error(transport: str = "rest"): - client = ChatServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, space.Space) for i in results) - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.update_membership( - gc_membership.UpdateMembershipRequest(), - membership=gc_membership.Membership(name="name_value"), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), - ) + pages = list(client.search_spaces(request=sample_request).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token -def test_delete_membership_rest_use_cached_wrapped_rpc(): +def test_get_space_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -17315,33 +18486,29 @@ def test_delete_membership_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.delete_membership in client._transport._wrapped_methods + assert client._transport.get_space in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = 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_membership] = ( - mock_rpc - ) + client._transport._wrapped_methods[client._transport.get_space] = mock_rpc request = {} - client.delete_membership(request) + client.get_space(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.delete_membership(request) + client.get_space(request) # Establish 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_membership_rest_required_fields( - request_type=membership.DeleteMembershipRequest, -): +def test_get_space_rest_required_fields(request_type=space.GetSpaceRequest): transport_class = transports.ChatServiceRestTransport request_init = {} @@ -17356,7 +18523,7 @@ def test_delete_membership_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).delete_membership._get_unset_required_fields(jsonified_request) + ).get_space._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present @@ -17365,7 +18532,7 @@ def test_delete_membership_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).delete_membership._get_unset_required_fields(jsonified_request) + ).get_space._get_unset_required_fields(jsonified_request) # Check that path parameters and body parameters are not mixing in. assert not set(unset_fields) - set(("use_admin_access",)) jsonified_request.update(unset_fields) @@ -17381,7 +18548,7 @@ def test_delete_membership_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = membership.Membership() + return_value = space.Space() # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values @@ -17393,7 +18560,7 @@ def test_delete_membership_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 @@ -17402,30 +18569,30 @@ def test_delete_membership_rest_required_fields( response_value.status_code = 200 # Convert return value to protobuf type - return_value = membership.Membership.pb(return_value) + return_value = space.Space.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_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_membership(request) + response = client.get_space(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_delete_membership_rest_unset_required_fields(): +def test_get_space_rest_unset_required_fields(): transport = transports.ChatServiceRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.delete_membership._get_unset_required_fields({}) + unset_fields = transport.get_space._get_unset_required_fields({}) assert set(unset_fields) == (set(("useAdminAccess",)) & set(("name",))) -def test_delete_membership_rest_flattened(): +def test_get_space_rest_flattened(): client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -17434,10 +18601,10 @@ def test_delete_membership_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 = membership.Membership() + return_value = space.Space() # get arguments that satisfy an http rule for this method - sample_request = {"name": "spaces/sample1/members/sample2"} + sample_request = {"name": "spaces/sample1"} # get truthy value for each flattened field mock_args = dict( @@ -17449,24 +18616,24 @@ def test_delete_membership_rest_flattened(): response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = membership.Membership.pb(return_value) + return_value = space.Space.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = 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_membership(**mock_args) + client.get_space(**mock_args) # Establish that the underlying call was 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=spaces/*/members/*}" % client.transport._host, args[1] + "%s/v1/{name=spaces/*}" % client.transport._host, args[1] ) -def test_delete_membership_rest_flattened_error(transport: str = "rest"): +def test_get_space_rest_flattened_error(transport: str = "rest"): client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -17475,13 +18642,13 @@ def test_delete_membership_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_membership( - membership.DeleteMembershipRequest(), + client.get_space( + space.GetSpaceRequest(), name="name_value", ) -def test_create_reaction_rest_use_cached_wrapped_rpc(): +def test_create_space_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -17495,35 +18662,32 @@ def test_create_reaction_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.create_reaction in client._transport._wrapped_methods + assert client._transport.create_space in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = 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_reaction] = mock_rpc + client._transport._wrapped_methods[client._transport.create_space] = mock_rpc request = {} - client.create_reaction(request) + client.create_space(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.create_reaction(request) + client.create_space(request) # Establish 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_reaction_rest_required_fields( - request_type=gc_reaction.CreateReactionRequest, -): +def test_create_space_rest_required_fields(request_type=gc_space.CreateSpaceRequest): transport_class = transports.ChatServiceRestTransport request_init = {} - request_init["parent"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -17534,21 +18698,19 @@ def test_create_reaction_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).create_reaction._get_unset_required_fields(jsonified_request) + ).create_space._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present - jsonified_request["parent"] = "parent_value" - unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).create_reaction._get_unset_required_fields(jsonified_request) + ).create_space._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("request_id",)) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == "parent_value" client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -17557,7 +18719,7 @@ def test_create_reaction_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = gc_reaction.Reaction() + return_value = gc_space.Space() # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values @@ -17579,38 +18741,30 @@ def test_create_reaction_rest_required_fields( response_value.status_code = 200 # Convert return value to protobuf type - return_value = gc_reaction.Reaction.pb(return_value) + return_value = gc_space.Space.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_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_reaction(request) + response = client.create_space(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_create_reaction_rest_unset_required_fields(): +def test_create_space_rest_unset_required_fields(): transport = transports.ChatServiceRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.create_reaction._get_unset_required_fields({}) - assert set(unset_fields) == ( - set(()) - & set( - ( - "parent", - "reaction", - ) - ) - ) + unset_fields = transport.create_space._get_unset_required_fields({}) + assert set(unset_fields) == (set(("requestId",)) & set(("space",))) -def test_create_reaction_rest_flattened(): +def test_create_space_rest_flattened(): client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -17619,15 +18773,14 @@ def test_create_reaction_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 = gc_reaction.Reaction() + return_value = gc_space.Space() # get arguments that satisfy an http rule for this method - sample_request = {"parent": "spaces/sample1/messages/sample2"} + sample_request = {} # get truthy value for each flattened field mock_args = dict( - parent="parent_value", - reaction=gc_reaction.Reaction(name="name_value"), + space=gc_space.Space(name="name_value"), ) mock_args.update(sample_request) @@ -17635,25 +18788,22 @@ def test_create_reaction_rest_flattened(): response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = gc_reaction.Reaction.pb(return_value) + return_value = gc_space.Space.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = 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_reaction(**mock_args) + client.create_space(**mock_args) # Establish that the underlying call was 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=spaces/*/messages/*}/reactions" % client.transport._host, - args[1], - ) + assert path_template.validate("%s/v1/spaces" % client.transport._host, args[1]) -def test_create_reaction_rest_flattened_error(transport: str = "rest"): +def test_create_space_rest_flattened_error(transport: str = "rest"): client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -17662,14 +18812,13 @@ def test_create_reaction_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_reaction( - gc_reaction.CreateReactionRequest(), - parent="parent_value", - reaction=gc_reaction.Reaction(name="name_value"), + client.create_space( + gc_space.CreateSpaceRequest(), + space=gc_space.Space(name="name_value"), ) -def test_list_reactions_rest_use_cached_wrapped_rpc(): +def test_set_up_space_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -17683,35 +18832,32 @@ def test_list_reactions_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.list_reactions in client._transport._wrapped_methods + assert client._transport.set_up_space in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = 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_reactions] = mock_rpc + client._transport._wrapped_methods[client._transport.set_up_space] = mock_rpc request = {} - client.list_reactions(request) + client.set_up_space(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.list_reactions(request) + client.set_up_space(request) # Establish 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_reactions_rest_required_fields( - request_type=reaction.ListReactionsRequest, -): +def test_set_up_space_rest_required_fields(request_type=space_setup.SetUpSpaceRequest): transport_class = transports.ChatServiceRestTransport request_init = {} - request_init["parent"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -17722,29 +18868,17 @@ def test_list_reactions_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).list_reactions._get_unset_required_fields(jsonified_request) + ).set_up_space._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present - jsonified_request["parent"] = "parent_value" - unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).list_reactions._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set( - ( - "filter", - "page_size", - "page_token", - ) - ) + ).set_up_space._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == "parent_value" client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -17753,7 +18887,7 @@ def test_list_reactions_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = reaction.ListReactionsResponse() + return_value = space.Space() # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values @@ -17765,166 +18899,232 @@ def test_list_reactions_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 = reaction.ListReactionsResponse.pb(return_value) + return_value = space.Space.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_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_reactions(request) + response = client.set_up_space(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_list_reactions_rest_unset_required_fields(): +def test_set_up_space_rest_unset_required_fields(): transport = transports.ChatServiceRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.list_reactions._get_unset_required_fields({}) - assert set(unset_fields) == ( - set( - ( - "filter", - "pageSize", - "pageToken", - ) - ) - & set(("parent",)) - ) + unset_fields = transport.set_up_space._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("space",))) -def test_list_reactions_rest_flattened(): - client = ChatServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) +def test_update_space_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), "request") as req: - # Designate an appropriate value for the returned response. - return_value = reaction.ListReactionsResponse() + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() - # get arguments that satisfy an http rule for this method - sample_request = {"parent": "spaces/sample1/messages/sample2"} + # Ensure method has been cached + assert client._transport.update_space in client._transport._wrapped_methods - # get truthy value for each flattened field - mock_args = dict( - 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_args.update(sample_request) + client._transport._wrapped_methods[client._transport.update_space] = mock_rpc - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = reaction.ListReactionsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._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 = {} + client.update_space(request) - client.list_reactions(**mock_args) + # 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(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate( - "%s/v1/{parent=spaces/*/messages/*}/reactions" % client.transport._host, - args[1], - ) + client.update_space(request) + # Establish 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_reactions_rest_flattened_error(transport: str = "rest"): - client = ChatServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, + +def test_update_space_rest_required_fields(request_type=gc_space.UpdateSpaceRequest): + transport_class = transports.ChatServiceRestTransport + + 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) ) - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.list_reactions( - reaction.ListReactionsRequest(), - parent="parent_value", + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).update_space._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).update_space._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "update_mask", + "use_admin_access", ) + ) + jsonified_request.update(unset_fields) + # verify required fields with non-default values are left alone -def test_list_reactions_rest_pager(transport: str = "rest"): client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport=transport, + transport="rest", ) + request = request_type(**request_init) + # Designate an appropriate value for the returned response. + return_value = gc_space.Space() # 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 = ( - reaction.ListReactionsResponse( - reactions=[ - reaction.Reaction(), - reaction.Reaction(), - reaction.Reaction(), - ], - next_page_token="abc", - ), - reaction.ListReactionsResponse( - reactions=[], - next_page_token="def", - ), - reaction.ListReactionsResponse( - reactions=[ - reaction.Reaction(), - ], - next_page_token="ghi", - ), - reaction.ListReactionsResponse( - reactions=[ - reaction.Reaction(), - reaction.Reaction(), - ], - ), + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force 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 = gc_space.Space.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_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_space(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_update_space_rest_unset_required_fields(): + transport = transports.ChatServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.update_space._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "updateMask", + "useAdminAccess", + ) ) - # Two responses for two calls - response = response + response + & set( + ( + "space", + "updateMask", + ) + ) + ) - # Wrap the values into proper Response objs - response = tuple(reaction.ListReactionsResponse.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": "spaces/sample1/messages/sample2"} +def test_update_space_rest_flattened(): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) - pager = client.list_reactions(request=sample_request) + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = gc_space.Space() - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, reaction.Reaction) for i in results) + # get arguments that satisfy an http rule for this method + sample_request = {"space": {"name": "spaces/sample1"}} - pages = list(client.list_reactions(request=sample_request).pages) - for page_, token in zip(pages, ["abc", "def", "ghi", ""]): - assert page_.raw_page.next_page_token == token + # get truthy value for each flattened field + mock_args = dict( + space=gc_space.Space(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 = gc_space.Space.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = 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_space(**mock_args) -def test_delete_reaction_rest_use_cached_wrapped_rpc(): + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1/{space.name=spaces/*}" % client.transport._host, args[1] + ) + + +def test_update_space_rest_flattened_error(transport: str = "rest"): + client = ChatServiceClient( + credentials=ga_credentials.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_space( + gc_space.UpdateSpaceRequest(), + space=gc_space.Space(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +def test_delete_space_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -17938,31 +19138,29 @@ def test_delete_reaction_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.delete_reaction in client._transport._wrapped_methods + assert client._transport.delete_space in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = 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_reaction] = mock_rpc + client._transport._wrapped_methods[client._transport.delete_space] = mock_rpc request = {} - client.delete_reaction(request) + client.delete_space(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.delete_reaction(request) + client.delete_space(request) # Establish 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_reaction_rest_required_fields( - request_type=reaction.DeleteReactionRequest, -): +def test_delete_space_rest_required_fields(request_type=space.DeleteSpaceRequest): transport_class = transports.ChatServiceRestTransport request_init = {} @@ -17977,7 +19175,7 @@ def test_delete_reaction_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).delete_reaction._get_unset_required_fields(jsonified_request) + ).delete_space._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present @@ -17986,7 +19184,9 @@ def test_delete_reaction_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).delete_reaction._get_unset_required_fields(jsonified_request) + ).delete_space._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("use_admin_access",)) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone @@ -18025,23 +19225,23 @@ def test_delete_reaction_rest_required_fields( req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.delete_reaction(request) + response = client.delete_space(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_delete_reaction_rest_unset_required_fields(): +def test_delete_space_rest_unset_required_fields(): transport = transports.ChatServiceRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.delete_reaction._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name",))) + unset_fields = transport.delete_space._get_unset_required_fields({}) + assert set(unset_fields) == (set(("useAdminAccess",)) & set(("name",))) -def test_delete_reaction_rest_flattened(): +def test_delete_space_rest_flattened(): client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -18053,7 +19253,7 @@ def test_delete_reaction_rest_flattened(): return_value = None # get arguments that satisfy an http rule for this method - sample_request = {"name": "spaces/sample1/messages/sample2/reactions/sample3"} + sample_request = {"name": "spaces/sample1"} # get truthy value for each flattened field mock_args = dict( @@ -18069,19 +19269,18 @@ def test_delete_reaction_rest_flattened(): req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.delete_reaction(**mock_args) + client.delete_space(**mock_args) # Establish that the underlying call was 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=spaces/*/messages/*/reactions/*}" % client.transport._host, - args[1], + "%s/v1/{name=spaces/*}" % client.transport._host, args[1] ) -def test_delete_reaction_rest_flattened_error(transport: str = "rest"): +def test_delete_space_rest_flattened_error(transport: str = "rest"): client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -18090,13 +19289,13 @@ def test_delete_reaction_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_reaction( - reaction.DeleteReactionRequest(), + client.delete_space( + space.DeleteSpaceRequest(), name="name_value", ) -def test_create_custom_emoji_rest_use_cached_wrapped_rpc(): +def test_complete_import_space_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -18111,7 +19310,8 @@ def test_create_custom_emoji_rest_use_cached_wrapped_rpc(): # Ensure method has been cached assert ( - client._transport.create_custom_emoji in client._transport._wrapped_methods + client._transport.complete_import_space + in client._transport._wrapped_methods ) # Replace cached wrapped function with mock @@ -18119,29 +19319,30 @@ def test_create_custom_emoji_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_custom_emoji] = ( + client._transport._wrapped_methods[client._transport.complete_import_space] = ( mock_rpc ) request = {} - client.create_custom_emoji(request) + client.complete_import_space(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.create_custom_emoji(request) + client.complete_import_space(request) # Establish 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_custom_emoji_rest_required_fields( - request_type=reaction.CreateCustomEmojiRequest, +def test_complete_import_space_rest_required_fields( + request_type=space.CompleteImportSpaceRequest, ): transport_class = transports.ChatServiceRestTransport request_init = {} + request_init["name"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -18152,17 +19353,21 @@ def test_create_custom_emoji_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).create_custom_emoji._get_unset_required_fields(jsonified_request) + ).complete_import_space._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present + jsonified_request["name"] = "name_value" + unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).create_custom_emoji._get_unset_required_fields(jsonified_request) + ).complete_import_space._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -18171,7 +19376,7 @@ def test_create_custom_emoji_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = reaction.CustomEmoji() + return_value = space.CompleteImportSpaceResponse() # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values @@ -18193,86 +19398,165 @@ def test_create_custom_emoji_rest_required_fields( response_value.status_code = 200 # Convert return value to protobuf type - return_value = reaction.CustomEmoji.pb(return_value) + return_value = space.CompleteImportSpaceResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_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_custom_emoji(request) + response = client.complete_import_space(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_create_custom_emoji_rest_unset_required_fields(): +def test_complete_import_space_rest_unset_required_fields(): transport = transports.ChatServiceRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.create_custom_emoji._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("customEmoji",))) + unset_fields = transport.complete_import_space._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) -def test_create_custom_emoji_rest_flattened(): - client = ChatServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) +def test_find_direct_message_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), "request") as req: - # Designate an appropriate value for the returned response. - return_value = reaction.CustomEmoji() + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() - # get arguments that satisfy an http rule for this method - sample_request = {} + # Ensure method has been cached + assert ( + client._transport.find_direct_message in client._transport._wrapped_methods + ) - # get truthy value for each flattened field - mock_args = dict( - custom_emoji=reaction.CustomEmoji(name="name_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.find_direct_message] = ( + mock_rpc ) - mock_args.update(sample_request) - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = reaction.CustomEmoji.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._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 = {} + client.find_direct_message(request) - client.create_custom_emoji(**mock_args) + # 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(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate( - "%s/v1/customEmojis" % client.transport._host, args[1] - ) + client.find_direct_message(request) + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_find_direct_message_rest_required_fields( + request_type=space.FindDirectMessageRequest, +): + transport_class = transports.ChatServiceRestTransport + + 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 + assert "name" not in jsonified_request + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).find_direct_message._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + assert "name" in jsonified_request + assert jsonified_request["name"] == request_init["name"] + + jsonified_request["name"] = "name_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).find_direct_message._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("name",)) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" -def test_create_custom_emoji_rest_flattened_error(transport: str = "rest"): client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport=transport, + transport="rest", ) + request = request_type(**request_init) - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.create_custom_emoji( - reaction.CreateCustomEmojiRequest(), - custom_emoji=reaction.CustomEmoji(name="name_value"), - ) + # Designate an appropriate value for the returned response. + return_value = space.Space() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_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 = space.Space.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) -def test_get_custom_emoji_rest_use_cached_wrapped_rpc(): + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.find_direct_message(request) + + expected_params = [ + ( + "name", + "", + ), + ("$alt", "json;enum-encoding=int"), + ] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_find_direct_message_rest_unset_required_fields(): + transport = transports.ChatServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.find_direct_message._get_unset_required_fields({}) + assert set(unset_fields) == (set(("name",)) & set(("name",))) + + +def test_create_membership_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -18286,37 +19570,37 @@ def test_get_custom_emoji_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.get_custom_emoji in client._transport._wrapped_methods + assert client._transport.create_membership in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = 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_custom_emoji] = ( + client._transport._wrapped_methods[client._transport.create_membership] = ( mock_rpc ) request = {} - client.get_custom_emoji(request) + client.create_membership(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.get_custom_emoji(request) + client.create_membership(request) # Establish 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_custom_emoji_rest_required_fields( - request_type=reaction.GetCustomEmojiRequest, +def test_create_membership_rest_required_fields( + request_type=gc_membership.CreateMembershipRequest, ): transport_class = transports.ChatServiceRestTransport request_init = {} - request_init["name"] = "" + request_init["parent"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -18327,21 +19611,23 @@ def test_get_custom_emoji_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).get_custom_emoji._get_unset_required_fields(jsonified_request) + ).create_membership._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present - jsonified_request["name"] = "name_value" + jsonified_request["parent"] = "parent_value" unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).get_custom_emoji._get_unset_required_fields(jsonified_request) + ).create_membership._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("use_admin_access",)) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == "name_value" + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -18350,7 +19636,7 @@ def test_get_custom_emoji_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = reaction.CustomEmoji() + return_value = gc_membership.Membership() # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values @@ -18362,39 +19648,48 @@ def test_get_custom_emoji_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 = reaction.CustomEmoji.pb(return_value) + return_value = gc_membership.Membership.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_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_custom_emoji(request) + response = client.create_membership(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_get_custom_emoji_rest_unset_required_fields(): +def test_create_membership_rest_unset_required_fields(): transport = transports.ChatServiceRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.get_custom_emoji._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name",))) + unset_fields = transport.create_membership._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(("useAdminAccess",)) + & set( + ( + "parent", + "membership", + ) + ) + ) -def test_get_custom_emoji_rest_flattened(): +def test_create_membership_rest_flattened(): client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -18403,14 +19698,15 @@ def test_get_custom_emoji_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 = reaction.CustomEmoji() + return_value = gc_membership.Membership() # get arguments that satisfy an http rule for this method - sample_request = {"name": "customEmojis/sample1"} + sample_request = {"parent": "spaces/sample1"} # get truthy value for each flattened field mock_args = dict( - name="name_value", + parent="parent_value", + membership=gc_membership.Membership(name="name_value"), ) mock_args.update(sample_request) @@ -18418,24 +19714,24 @@ def test_get_custom_emoji_rest_flattened(): response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = reaction.CustomEmoji.pb(return_value) + return_value = gc_membership.Membership.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = 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_custom_emoji(**mock_args) + client.create_membership(**mock_args) # Establish that the underlying call was 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=customEmojis/*}" % client.transport._host, args[1] + "%s/v1/{parent=spaces/*}/members" % client.transport._host, args[1] ) -def test_get_custom_emoji_rest_flattened_error(transport: str = "rest"): +def test_create_membership_rest_flattened_error(transport: str = "rest"): client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -18444,13 +19740,14 @@ def test_get_custom_emoji_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_custom_emoji( - reaction.GetCustomEmojiRequest(), - name="name_value", + client.create_membership( + gc_membership.CreateMembershipRequest(), + parent="parent_value", + membership=gc_membership.Membership(name="name_value"), ) -def test_list_custom_emojis_rest_use_cached_wrapped_rpc(): +def test_update_membership_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -18464,165 +19761,64 @@ def test_list_custom_emojis_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert ( - client._transport.list_custom_emojis in client._transport._wrapped_methods - ) + assert client._transport.update_membership in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = 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_custom_emojis] = ( + client._transport._wrapped_methods[client._transport.update_membership] = ( mock_rpc ) request = {} - client.list_custom_emojis(request) + client.update_membership(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.list_custom_emojis(request) + client.update_membership(request) # Establish 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_custom_emojis_rest_pager(transport: str = "rest"): - client = ChatServiceClient( - 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 = ( - reaction.ListCustomEmojisResponse( - custom_emojis=[ - reaction.CustomEmoji(), - reaction.CustomEmoji(), - reaction.CustomEmoji(), - ], - next_page_token="abc", - ), - reaction.ListCustomEmojisResponse( - custom_emojis=[], - next_page_token="def", - ), - reaction.ListCustomEmojisResponse( - custom_emojis=[ - reaction.CustomEmoji(), - ], - next_page_token="ghi", - ), - reaction.ListCustomEmojisResponse( - custom_emojis=[ - reaction.CustomEmoji(), - reaction.CustomEmoji(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(reaction.ListCustomEmojisResponse.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 = {} - - pager = client.list_custom_emojis(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, reaction.CustomEmoji) for i in results) - - pages = list(client.list_custom_emojis(request=sample_request).pages) - for page_, token in zip(pages, ["abc", "def", "ghi", ""]): - assert page_.raw_page.next_page_token == token - - -def test_delete_custom_emoji_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = ChatServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should 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_custom_emoji in client._transport._wrapped_methods - ) - - # Replace cached wrapped function with mock - mock_rpc = 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_custom_emoji] = ( - mock_rpc - ) - - request = {} - client.delete_custom_emoji(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.delete_custom_emoji(request) - - # Establish 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_custom_emoji_rest_required_fields( - request_type=reaction.DeleteCustomEmojiRequest, -): - transport_class = transports.ChatServiceRestTransport - - 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_update_membership_rest_required_fields( + request_type=gc_membership.UpdateMembershipRequest, +): + transport_class = transports.ChatServiceRestTransport + + request_init = {} + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) ) # verify fields with default values are dropped unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).delete_custom_emoji._get_unset_required_fields(jsonified_request) + ).update_membership._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present - jsonified_request["name"] = "name_value" - unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).delete_custom_emoji._get_unset_required_fields(jsonified_request) + ).update_membership._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "update_mask", + "use_admin_access", + ) + ) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == "name_value" client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -18631,7 +19827,7 @@ def test_delete_custom_emoji_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = None + return_value = gc_membership.Membership() # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values @@ -18643,36 +19839,53 @@ def test_delete_custom_emoji_rest_required_fields( pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "delete", + "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 = "" + + # Convert return value to protobuf type + return_value = gc_membership.Membership.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) response_value._content = json_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_custom_emoji(request) + response = client.update_membership(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_delete_custom_emoji_rest_unset_required_fields(): +def test_update_membership_rest_unset_required_fields(): transport = transports.ChatServiceRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.delete_custom_emoji._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name",))) + unset_fields = transport.update_membership._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "updateMask", + "useAdminAccess", + ) + ) + & set( + ( + "membership", + "updateMask", + ) + ) + ) -def test_delete_custom_emoji_rest_flattened(): +def test_update_membership_rest_flattened(): client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -18681,37 +19894,41 @@ def test_delete_custom_emoji_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 = None + return_value = gc_membership.Membership() # get arguments that satisfy an http rule for this method - sample_request = {"name": "customEmojis/sample1"} + sample_request = {"membership": {"name": "spaces/sample1/members/sample2"}} # get truthy value for each flattened field mock_args = dict( - name="name_value", + membership=gc_membership.Membership(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 = "" + # Convert return value to protobuf type + return_value = gc_membership.Membership.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) response_value._content = 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_custom_emoji(**mock_args) + client.update_membership(**mock_args) # Establish that the underlying call was 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=customEmojis/*}" % client.transport._host, args[1] + "%s/v1/{membership.name=spaces/*/members/*}" % client.transport._host, + args[1], ) -def test_delete_custom_emoji_rest_flattened_error(transport: str = "rest"): +def test_update_membership_rest_flattened_error(transport: str = "rest"): client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -18720,13 +19937,14 @@ def test_delete_custom_emoji_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_custom_emoji( - reaction.DeleteCustomEmojiRequest(), - name="name_value", + client.update_membership( + gc_membership.UpdateMembershipRequest(), + membership=gc_membership.Membership(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) -def test_get_space_read_state_rest_use_cached_wrapped_rpc(): +def test_delete_membership_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -18740,34 +19958,32 @@ def test_get_space_read_state_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert ( - client._transport.get_space_read_state in client._transport._wrapped_methods - ) + assert client._transport.delete_membership in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = 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_space_read_state] = ( + client._transport._wrapped_methods[client._transport.delete_membership] = ( mock_rpc ) request = {} - client.get_space_read_state(request) + client.delete_membership(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.get_space_read_state(request) + client.delete_membership(request) # Establish 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_space_read_state_rest_required_fields( - request_type=space_read_state.GetSpaceReadStateRequest, +def test_delete_membership_rest_required_fields( + request_type=membership.DeleteMembershipRequest, ): transport_class = transports.ChatServiceRestTransport @@ -18783,7 +19999,7 @@ def test_get_space_read_state_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).get_space_read_state._get_unset_required_fields(jsonified_request) + ).delete_membership._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present @@ -18792,7 +20008,9 @@ def test_get_space_read_state_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).get_space_read_state._get_unset_required_fields(jsonified_request) + ).delete_membership._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("use_admin_access",)) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone @@ -18806,7 +20024,7 @@ def test_get_space_read_state_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = space_read_state.SpaceReadState() + return_value = membership.Membership() # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values @@ -18818,7 +20036,7 @@ def test_get_space_read_state_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 @@ -18827,30 +20045,30 @@ def test_get_space_read_state_rest_required_fields( response_value.status_code = 200 # Convert return value to protobuf type - return_value = space_read_state.SpaceReadState.pb(return_value) + return_value = membership.Membership.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_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_space_read_state(request) + response = client.delete_membership(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_get_space_read_state_rest_unset_required_fields(): +def test_delete_membership_rest_unset_required_fields(): transport = transports.ChatServiceRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.get_space_read_state._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name",))) + unset_fields = transport.delete_membership._get_unset_required_fields({}) + assert set(unset_fields) == (set(("useAdminAccess",)) & set(("name",))) -def test_get_space_read_state_rest_flattened(): +def test_delete_membership_rest_flattened(): client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -18859,10 +20077,10 @@ def test_get_space_read_state_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 = space_read_state.SpaceReadState() + return_value = membership.Membership() # get arguments that satisfy an http rule for this method - sample_request = {"name": "users/sample1/spaces/sample2/spaceReadState"} + sample_request = {"name": "spaces/sample1/members/sample2"} # get truthy value for each flattened field mock_args = dict( @@ -18874,25 +20092,24 @@ def test_get_space_read_state_rest_flattened(): response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = space_read_state.SpaceReadState.pb(return_value) + return_value = membership.Membership.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = 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_space_read_state(**mock_args) + client.delete_membership(**mock_args) # Establish that the underlying call was 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=users/*/spaces/*/spaceReadState}" % client.transport._host, - args[1], + "%s/v1/{name=spaces/*/members/*}" % client.transport._host, args[1] ) -def test_get_space_read_state_rest_flattened_error(transport: str = "rest"): +def test_delete_membership_rest_flattened_error(transport: str = "rest"): client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -18901,13 +20118,13 @@ def test_get_space_read_state_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_space_read_state( - space_read_state.GetSpaceReadStateRequest(), + client.delete_membership( + membership.DeleteMembershipRequest(), name="name_value", ) -def test_update_space_read_state_rest_use_cached_wrapped_rpc(): +def test_create_reaction_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -18921,39 +20138,35 @@ def test_update_space_read_state_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert ( - client._transport.update_space_read_state - in client._transport._wrapped_methods - ) + assert client._transport.create_reaction in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = 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_space_read_state - ] = mock_rpc + client._transport._wrapped_methods[client._transport.create_reaction] = mock_rpc request = {} - client.update_space_read_state(request) + client.create_reaction(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.update_space_read_state(request) + client.create_reaction(request) # Establish 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_space_read_state_rest_required_fields( - request_type=gc_space_read_state.UpdateSpaceReadStateRequest, +def test_create_reaction_rest_required_fields( + request_type=gc_reaction.CreateReactionRequest, ): transport_class = transports.ChatServiceRestTransport request_init = {} + request_init["parent"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -18964,19 +20177,21 @@ def test_update_space_read_state_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).update_space_read_state._get_unset_required_fields(jsonified_request) + ).create_reaction._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present + jsonified_request["parent"] = "parent_value" + unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).update_space_read_state._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("update_mask",)) + ).create_reaction._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -18985,7 +20200,7 @@ def test_update_space_read_state_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = gc_space_read_state.SpaceReadState() + return_value = gc_reaction.Reaction() # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values @@ -18997,7 +20212,7 @@ def test_update_space_read_state_rest_required_fields( pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "patch", + "method": "post", "query_params": pb_request, } transcode_result["body"] = pb_request @@ -19007,38 +20222,38 @@ def test_update_space_read_state_rest_required_fields( response_value.status_code = 200 # Convert return value to protobuf type - return_value = gc_space_read_state.SpaceReadState.pb(return_value) + return_value = gc_reaction.Reaction.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_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_space_read_state(request) + response = client.create_reaction(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_update_space_read_state_rest_unset_required_fields(): +def test_create_reaction_rest_unset_required_fields(): transport = transports.ChatServiceRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.update_space_read_state._get_unset_required_fields({}) + unset_fields = transport.create_reaction._get_unset_required_fields({}) assert set(unset_fields) == ( - set(("updateMask",)) + set(()) & set( ( - "spaceReadState", - "updateMask", + "parent", + "reaction", ) ) ) -def test_update_space_read_state_rest_flattened(): +def test_create_reaction_rest_flattened(): client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -19047,17 +20262,15 @@ def test_update_space_read_state_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 = gc_space_read_state.SpaceReadState() + return_value = gc_reaction.Reaction() # get arguments that satisfy an http rule for this method - sample_request = { - "space_read_state": {"name": "users/sample1/spaces/sample2/spaceReadState"} - } + sample_request = {"parent": "spaces/sample1/messages/sample2"} # get truthy value for each flattened field mock_args = dict( - space_read_state=gc_space_read_state.SpaceReadState(name="name_value"), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + parent="parent_value", + reaction=gc_reaction.Reaction(name="name_value"), ) mock_args.update(sample_request) @@ -19065,26 +20278,25 @@ def test_update_space_read_state_rest_flattened(): response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = gc_space_read_state.SpaceReadState.pb(return_value) + return_value = gc_reaction.Reaction.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = 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_space_read_state(**mock_args) + client.create_reaction(**mock_args) # Establish that the underlying call was made with the expected # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] assert path_template.validate( - "%s/v1/{space_read_state.name=users/*/spaces/*/spaceReadState}" - % client.transport._host, + "%s/v1/{parent=spaces/*/messages/*}/reactions" % client.transport._host, args[1], ) -def test_update_space_read_state_rest_flattened_error(transport: str = "rest"): +def test_create_reaction_rest_flattened_error(transport: str = "rest"): client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -19093,14 +20305,14 @@ def test_update_space_read_state_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_space_read_state( - gc_space_read_state.UpdateSpaceReadStateRequest(), - space_read_state=gc_space_read_state.SpaceReadState(name="name_value"), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + client.create_reaction( + gc_reaction.CreateReactionRequest(), + parent="parent_value", + reaction=gc_reaction.Reaction(name="name_value"), ) -def test_get_thread_read_state_rest_use_cached_wrapped_rpc(): +def test_list_reactions_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -19114,40 +20326,35 @@ def test_get_thread_read_state_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert ( - client._transport.get_thread_read_state - in client._transport._wrapped_methods - ) + assert client._transport.list_reactions in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = 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_thread_read_state] = ( - mock_rpc - ) + client._transport._wrapped_methods[client._transport.list_reactions] = mock_rpc request = {} - client.get_thread_read_state(request) + client.list_reactions(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.get_thread_read_state(request) + client.list_reactions(request) # Establish 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_thread_read_state_rest_required_fields( - request_type=thread_read_state.GetThreadReadStateRequest, +def test_list_reactions_rest_required_fields( + request_type=reaction.ListReactionsRequest, ): transport_class = transports.ChatServiceRestTransport request_init = {} - request_init["name"] = "" + request_init["parent"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -19158,21 +20365,29 @@ def test_get_thread_read_state_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).get_thread_read_state._get_unset_required_fields(jsonified_request) + ).list_reactions._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present - jsonified_request["name"] = "name_value" + jsonified_request["parent"] = "parent_value" unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).get_thread_read_state._get_unset_required_fields(jsonified_request) + ).list_reactions._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "filter", + "page_size", + "page_token", + ) + ) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == "name_value" + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -19181,7 +20396,7 @@ def test_get_thread_read_state_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = thread_read_state.ThreadReadState() + return_value = reaction.ListReactionsResponse() # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values @@ -19202,30 +20417,39 @@ def test_get_thread_read_state_rest_required_fields( response_value.status_code = 200 # Convert return value to protobuf type - return_value = thread_read_state.ThreadReadState.pb(return_value) + return_value = reaction.ListReactionsResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_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_thread_read_state(request) + response = client.list_reactions(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_get_thread_read_state_rest_unset_required_fields(): +def test_list_reactions_rest_unset_required_fields(): transport = transports.ChatServiceRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.get_thread_read_state._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name",))) + unset_fields = transport.list_reactions._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "filter", + "pageSize", + "pageToken", + ) + ) + & set(("parent",)) + ) -def test_get_thread_read_state_rest_flattened(): +def test_list_reactions_rest_flattened(): client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -19234,16 +20458,14 @@ def test_get_thread_read_state_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 = thread_read_state.ThreadReadState() + return_value = reaction.ListReactionsResponse() # get arguments that satisfy an http rule for this method - sample_request = { - "name": "users/sample1/spaces/sample2/threads/sample3/threadReadState" - } + sample_request = {"parent": "spaces/sample1/messages/sample2"} # get truthy value for each flattened field mock_args = dict( - name="name_value", + parent="parent_value", ) mock_args.update(sample_request) @@ -19251,26 +20473,25 @@ def test_get_thread_read_state_rest_flattened(): response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = thread_read_state.ThreadReadState.pb(return_value) + return_value = reaction.ListReactionsResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = 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_thread_read_state(**mock_args) + client.list_reactions(**mock_args) # Establish that the underlying call was 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=users/*/spaces/*/threads/*/threadReadState}" - % client.transport._host, + "%s/v1/{parent=spaces/*/messages/*}/reactions" % client.transport._host, args[1], ) -def test_get_thread_read_state_rest_flattened_error(transport: str = "rest"): +def test_list_reactions_rest_flattened_error(transport: str = "rest"): client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -19279,13 +20500,74 @@ def test_get_thread_read_state_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_thread_read_state( - thread_read_state.GetThreadReadStateRequest(), - name="name_value", + client.list_reactions( + reaction.ListReactionsRequest(), + parent="parent_value", ) -def test_get_space_event_rest_use_cached_wrapped_rpc(): +def test_list_reactions_rest_pager(transport: str = "rest"): + client = ChatServiceClient( + 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 = ( + reaction.ListReactionsResponse( + reactions=[ + reaction.Reaction(), + reaction.Reaction(), + reaction.Reaction(), + ], + next_page_token="abc", + ), + reaction.ListReactionsResponse( + reactions=[], + next_page_token="def", + ), + reaction.ListReactionsResponse( + reactions=[ + reaction.Reaction(), + ], + next_page_token="ghi", + ), + reaction.ListReactionsResponse( + reactions=[ + reaction.Reaction(), + reaction.Reaction(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(reaction.ListReactionsResponse.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": "spaces/sample1/messages/sample2"} + + pager = client.list_reactions(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, reaction.Reaction) for i in results) + + pages = list(client.list_reactions(request=sample_request).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +def test_delete_reaction_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -19299,30 +20581,30 @@ def test_get_space_event_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.get_space_event in client._transport._wrapped_methods + assert client._transport.delete_reaction in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = 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_space_event] = mock_rpc + client._transport._wrapped_methods[client._transport.delete_reaction] = mock_rpc request = {} - client.get_space_event(request) + client.delete_reaction(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.get_space_event(request) + client.delete_reaction(request) # Establish 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_space_event_rest_required_fields( - request_type=space_event.GetSpaceEventRequest, +def test_delete_reaction_rest_required_fields( + request_type=reaction.DeleteReactionRequest, ): transport_class = transports.ChatServiceRestTransport @@ -19338,7 +20620,7 @@ def test_get_space_event_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).get_space_event._get_unset_required_fields(jsonified_request) + ).delete_reaction._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present @@ -19347,7 +20629,7 @@ def test_get_space_event_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).get_space_event._get_unset_required_fields(jsonified_request) + ).delete_reaction._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone @@ -19361,7 +20643,7 @@ def test_get_space_event_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = space_event.SpaceEvent() + 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 @@ -19373,39 +20655,36 @@ def test_get_space_event_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 = space_event.SpaceEvent.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) + json_return_value = "" response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.get_space_event(request) + response = client.delete_reaction(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_get_space_event_rest_unset_required_fields(): +def test_delete_reaction_rest_unset_required_fields(): transport = transports.ChatServiceRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.get_space_event._get_unset_required_fields({}) + unset_fields = transport.delete_reaction._get_unset_required_fields({}) assert set(unset_fields) == (set(()) & set(("name",))) -def test_get_space_event_rest_flattened(): +def test_delete_reaction_rest_flattened(): client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -19414,10 +20693,10 @@ def test_get_space_event_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 = space_event.SpaceEvent() + return_value = None # get arguments that satisfy an http rule for this method - sample_request = {"name": "spaces/sample1/spaceEvents/sample2"} + sample_request = {"name": "spaces/sample1/messages/sample2/reactions/sample3"} # get truthy value for each flattened field mock_args = dict( @@ -19428,25 +20707,24 @@ def test_get_space_event_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 = space_event.SpaceEvent.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) + json_return_value = "" response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.get_space_event(**mock_args) + client.delete_reaction(**mock_args) # Establish that the underlying call was 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=spaces/*/spaceEvents/*}" % client.transport._host, args[1] + "%s/v1/{name=spaces/*/messages/*/reactions/*}" % client.transport._host, + args[1], ) -def test_get_space_event_rest_flattened_error(transport: str = "rest"): +def test_delete_reaction_rest_flattened_error(transport: str = "rest"): client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -19455,13 +20733,13 @@ def test_get_space_event_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_space_event( - space_event.GetSpaceEventRequest(), + client.delete_reaction( + reaction.DeleteReactionRequest(), name="name_value", ) -def test_list_space_events_rest_use_cached_wrapped_rpc(): +def test_create_custom_emoji_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -19475,38 +20753,38 @@ def test_list_space_events_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.list_space_events in client._transport._wrapped_methods + assert ( + client._transport.create_custom_emoji in client._transport._wrapped_methods + ) # Replace cached wrapped function with mock mock_rpc = 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_space_events] = ( + client._transport._wrapped_methods[client._transport.create_custom_emoji] = ( mock_rpc ) request = {} - client.list_space_events(request) + client.create_custom_emoji(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.list_space_events(request) + client.create_custom_emoji(request) # Establish 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_space_events_rest_required_fields( - request_type=space_event.ListSpaceEventsRequest, +def test_create_custom_emoji_rest_required_fields( + request_type=reaction.CreateCustomEmojiRequest, ): transport_class = transports.ChatServiceRestTransport request_init = {} - request_init["parent"] = "" - request_init["filter"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -19514,38 +20792,20 @@ def test_list_space_events_rest_required_fields( ) # verify fields with default values are dropped - assert "filter" not in jsonified_request unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).list_space_events._get_unset_required_fields(jsonified_request) + ).create_custom_emoji._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present - assert "filter" in jsonified_request - assert jsonified_request["filter"] == request_init["filter"] - - jsonified_request["parent"] = "parent_value" - jsonified_request["filter"] = "filter_value" unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).list_space_events._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set( - ( - "filter", - "page_size", - "page_token", - ) - ) + ).create_custom_emoji._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == "parent_value" - assert "filter" in jsonified_request - assert jsonified_request["filter"] == "filter_value" client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -19554,7 +20814,7 @@ def test_list_space_events_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = space_event.ListSpaceEventsResponse() + return_value = reaction.CustomEmoji() # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values @@ -19566,59 +20826,40 @@ def test_list_space_events_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 = space_event.ListSpaceEventsResponse.pb(return_value) + return_value = reaction.CustomEmoji.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_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_space_events(request) + response = client.create_custom_emoji(request) - expected_params = [ - ( - "filter", - "", - ), - ("$alt", "json;enum-encoding=int"), - ] + expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_list_space_events_rest_unset_required_fields(): +def test_create_custom_emoji_rest_unset_required_fields(): transport = transports.ChatServiceRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.list_space_events._get_unset_required_fields({}) - assert set(unset_fields) == ( - set( - ( - "filter", - "pageSize", - "pageToken", - ) - ) - & set( - ( - "parent", - "filter", - ) - ) - ) + unset_fields = transport.create_custom_emoji._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("customEmoji",))) -def test_list_space_events_rest_flattened(): +def test_create_custom_emoji_rest_flattened(): client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -19627,15 +20868,14 @@ def test_list_space_events_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 = space_event.ListSpaceEventsResponse() + return_value = reaction.CustomEmoji() # get arguments that satisfy an http rule for this method - sample_request = {"parent": "spaces/sample1"} + sample_request = {} # get truthy value for each flattened field mock_args = dict( - parent="parent_value", - filter="filter_value", + custom_emoji=reaction.CustomEmoji(name="name_value"), ) mock_args.update(sample_request) @@ -19643,24 +20883,24 @@ def test_list_space_events_rest_flattened(): response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = space_event.ListSpaceEventsResponse.pb(return_value) + return_value = reaction.CustomEmoji.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = 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_space_events(**mock_args) + client.create_custom_emoji(**mock_args) # Establish that the underlying call was 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=spaces/*}/spaceEvents" % client.transport._host, args[1] + "%s/v1/customEmojis" % client.transport._host, args[1] ) -def test_list_space_events_rest_flattened_error(transport: str = "rest"): +def test_create_custom_emoji_rest_flattened_error(transport: str = "rest"): client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -19669,77 +20909,13 @@ def test_list_space_events_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_space_events( - space_event.ListSpaceEventsRequest(), - parent="parent_value", - filter="filter_value", - ) - - -def test_list_space_events_rest_pager(transport: str = "rest"): - client = ChatServiceClient( - 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 = ( - space_event.ListSpaceEventsResponse( - space_events=[ - space_event.SpaceEvent(), - space_event.SpaceEvent(), - space_event.SpaceEvent(), - ], - next_page_token="abc", - ), - space_event.ListSpaceEventsResponse( - space_events=[], - next_page_token="def", - ), - space_event.ListSpaceEventsResponse( - space_events=[ - space_event.SpaceEvent(), - ], - next_page_token="ghi", - ), - space_event.ListSpaceEventsResponse( - space_events=[ - space_event.SpaceEvent(), - space_event.SpaceEvent(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple( - space_event.ListSpaceEventsResponse.to_json(x) for x in response + client.create_custom_emoji( + reaction.CreateCustomEmojiRequest(), + custom_emoji=reaction.CustomEmoji(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": "spaces/sample1"} - - pager = client.list_space_events(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, space_event.SpaceEvent) for i in results) - - pages = list(client.list_space_events(request=sample_request).pages) - for page_, token in zip(pages, ["abc", "def", "ghi", ""]): - assert page_.raw_page.next_page_token == token -def test_get_space_notification_setting_rest_use_cached_wrapped_rpc(): +def test_get_custom_emoji_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -19753,35 +20929,32 @@ def test_get_space_notification_setting_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert ( - client._transport.get_space_notification_setting - in client._transport._wrapped_methods - ) + assert client._transport.get_custom_emoji in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = 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_space_notification_setting - ] = mock_rpc + client._transport._wrapped_methods[client._transport.get_custom_emoji] = ( + mock_rpc + ) request = {} - client.get_space_notification_setting(request) + client.get_custom_emoji(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.get_space_notification_setting(request) + client.get_custom_emoji(request) # Establish 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_space_notification_setting_rest_required_fields( - request_type=space_notification_setting.GetSpaceNotificationSettingRequest, +def test_get_custom_emoji_rest_required_fields( + request_type=reaction.GetCustomEmojiRequest, ): transport_class = transports.ChatServiceRestTransport @@ -19797,7 +20970,7 @@ def test_get_space_notification_setting_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).get_space_notification_setting._get_unset_required_fields(jsonified_request) + ).get_custom_emoji._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present @@ -19806,7 +20979,7 @@ def test_get_space_notification_setting_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).get_space_notification_setting._get_unset_required_fields(jsonified_request) + ).get_custom_emoji._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone @@ -19820,7 +20993,7 @@ def test_get_space_notification_setting_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = space_notification_setting.SpaceNotificationSetting() + return_value = reaction.CustomEmoji() # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values @@ -19841,34 +21014,30 @@ def test_get_space_notification_setting_rest_required_fields( response_value.status_code = 200 # Convert return value to protobuf type - return_value = space_notification_setting.SpaceNotificationSetting.pb( - return_value - ) + return_value = reaction.CustomEmoji.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_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_space_notification_setting(request) + response = client.get_custom_emoji(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_get_space_notification_setting_rest_unset_required_fields(): +def test_get_custom_emoji_rest_unset_required_fields(): transport = transports.ChatServiceRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.get_space_notification_setting._get_unset_required_fields( - {} - ) + unset_fields = transport.get_custom_emoji._get_unset_required_fields({}) assert set(unset_fields) == (set(()) & set(("name",))) -def test_get_space_notification_setting_rest_flattened(): +def test_get_custom_emoji_rest_flattened(): client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -19877,12 +21046,10 @@ def test_get_space_notification_setting_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 = space_notification_setting.SpaceNotificationSetting() + return_value = reaction.CustomEmoji() # get arguments that satisfy an http rule for this method - sample_request = { - "name": "users/sample1/spaces/sample2/spaceNotificationSetting" - } + sample_request = {"name": "customEmojis/sample1"} # get truthy value for each flattened field mock_args = dict( @@ -19894,28 +21061,24 @@ def test_get_space_notification_setting_rest_flattened(): response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = space_notification_setting.SpaceNotificationSetting.pb( - return_value - ) + return_value = reaction.CustomEmoji.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = 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_space_notification_setting(**mock_args) + client.get_custom_emoji(**mock_args) # Establish that the underlying call was 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=users/*/spaces/*/spaceNotificationSetting}" - % client.transport._host, - args[1], + "%s/v1/{name=customEmojis/*}" % client.transport._host, args[1] ) -def test_get_space_notification_setting_rest_flattened_error(transport: str = "rest"): +def test_get_custom_emoji_rest_flattened_error(transport: str = "rest"): client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -19924,13 +21087,13 @@ def test_get_space_notification_setting_rest_flattened_error(transport: str = "r # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.get_space_notification_setting( - space_notification_setting.GetSpaceNotificationSettingRequest(), + client.get_custom_emoji( + reaction.GetCustomEmojiRequest(), name="name_value", ) -def test_update_space_notification_setting_rest_use_cached_wrapped_rpc(): +def test_list_custom_emojis_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -19945,8 +21108,7 @@ def test_update_space_notification_setting_rest_use_cached_wrapped_rpc(): # Ensure method has been cached assert ( - client._transport.update_space_notification_setting - in client._transport._wrapped_methods + client._transport.list_custom_emojis in client._transport._wrapped_methods ) # Replace cached wrapped function with mock @@ -19954,61 +21116,165 @@ def test_update_space_notification_setting_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_space_notification_setting - ] = mock_rpc + client._transport._wrapped_methods[client._transport.list_custom_emojis] = ( + mock_rpc + ) request = {} - client.update_space_notification_setting(request) + client.list_custom_emojis(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.update_space_notification_setting(request) + client.list_custom_emojis(request) # Establish 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_space_notification_setting_rest_required_fields( - request_type=gc_space_notification_setting.UpdateSpaceNotificationSettingRequest, -): - transport_class = transports.ChatServiceRestTransport - - request_init = {} - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads( - json_format.MessageToJson(pb_request, use_integers_for_enums=False) - ) - - # verify fields with default values are dropped - - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).update_space_notification_setting._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).update_space_notification_setting._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("update_mask",)) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - +def test_list_custom_emojis_rest_pager(transport: str = "rest"): client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport=transport, ) - 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: + # 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 = ( + reaction.ListCustomEmojisResponse( + custom_emojis=[ + reaction.CustomEmoji(), + reaction.CustomEmoji(), + reaction.CustomEmoji(), + ], + next_page_token="abc", + ), + reaction.ListCustomEmojisResponse( + custom_emojis=[], + next_page_token="def", + ), + reaction.ListCustomEmojisResponse( + custom_emojis=[ + reaction.CustomEmoji(), + ], + next_page_token="ghi", + ), + reaction.ListCustomEmojisResponse( + custom_emojis=[ + reaction.CustomEmoji(), + reaction.CustomEmoji(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(reaction.ListCustomEmojisResponse.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 = {} + + pager = client.list_custom_emojis(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, reaction.CustomEmoji) for i in results) + + pages = list(client.list_custom_emojis(request=sample_request).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +def test_delete_custom_emoji_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should 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_custom_emoji in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = 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_custom_emoji] = ( + mock_rpc + ) + + request = {} + client.delete_custom_emoji(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.delete_custom_emoji(request) + + # Establish 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_custom_emoji_rest_required_fields( + request_type=reaction.DeleteCustomEmojiRequest, +): + transport_class = transports.ChatServiceRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).delete_custom_emoji._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).delete_custom_emoji._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = gc_space_notification_setting.SpaceNotificationSetting() + 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 @@ -20020,52 +21286,36 @@ def test_update_space_notification_setting_rest_required_fields( pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "patch", + "method": "delete", "query_params": pb_request, } - transcode_result["body"] = pb_request transcode.return_value = transcode_result response_value = Response() response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = gc_space_notification_setting.SpaceNotificationSetting.pb( - return_value - ) - json_return_value = json_format.MessageToJson(return_value) + json_return_value = "" response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.update_space_notification_setting(request) + response = client.delete_custom_emoji(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_update_space_notification_setting_rest_unset_required_fields(): +def test_delete_custom_emoji_rest_unset_required_fields(): transport = transports.ChatServiceRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = ( - transport.update_space_notification_setting._get_unset_required_fields({}) - ) - assert set(unset_fields) == ( - set(("updateMask",)) - & set( - ( - "spaceNotificationSetting", - "updateMask", - ) - ) - ) + unset_fields = transport.delete_custom_emoji._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) -def test_update_space_notification_setting_rest_flattened(): +def test_delete_custom_emoji_rest_flattened(): client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -20074,52 +21324,37 @@ def test_update_space_notification_setting_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 = gc_space_notification_setting.SpaceNotificationSetting() + return_value = None # get arguments that satisfy an http rule for this method - sample_request = { - "space_notification_setting": { - "name": "users/sample1/spaces/sample2/spaceNotificationSetting" - } - } + sample_request = {"name": "customEmojis/sample1"} # get truthy value for each flattened field mock_args = dict( - space_notification_setting=gc_space_notification_setting.SpaceNotificationSetting( - name="name_value" - ), - 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 = gc_space_notification_setting.SpaceNotificationSetting.pb( - return_value - ) - json_return_value = json_format.MessageToJson(return_value) + json_return_value = "" response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.update_space_notification_setting(**mock_args) + client.delete_custom_emoji(**mock_args) # Establish that the underlying call was made with the expected # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] assert path_template.validate( - "%s/v1/{space_notification_setting.name=users/*/spaces/*/spaceNotificationSetting}" - % client.transport._host, - args[1], + "%s/v1/{name=customEmojis/*}" % client.transport._host, args[1] ) -def test_update_space_notification_setting_rest_flattened_error( - transport: str = "rest", -): +def test_delete_custom_emoji_rest_flattened_error(transport: str = "rest"): client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -20128,2141 +21363,5256 @@ def test_update_space_notification_setting_rest_flattened_error( # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.update_space_notification_setting( - gc_space_notification_setting.UpdateSpaceNotificationSettingRequest(), - space_notification_setting=gc_space_notification_setting.SpaceNotificationSetting( - name="name_value" - ), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + client.delete_custom_emoji( + reaction.DeleteCustomEmojiRequest(), + name="name_value", ) -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.ChatServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): +def test_get_space_read_state_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport=transport, + transport="rest", ) - # It is an error to provide a credentials file and a transport instance. - transport = transports.ChatServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = ChatServiceClient( - 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.ChatServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = ChatServiceClient( - client_options=options, - transport=transport, + # Ensure method has been cached + assert ( + client._transport.get_space_read_state 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 = ChatServiceClient( - client_options=options, credentials=ga_credentials.AnonymousCredentials() - ) - - # It is an error to provide scopes and a transport instance. - transport = transports.ChatServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = ChatServiceClient( - client_options={"scopes": ["1", "2"]}, - 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_space_read_state] = ( + mock_rpc ) + request = {} + client.get_space_read_state(request) -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.ChatServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = ChatServiceClient(transport=transport) - assert client.transport is transport + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + client.get_space_read_state(request) -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.ChatServiceGrpcTransport( - 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.ChatServiceGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel +def test_get_space_read_state_rest_required_fields( + request_type=space_read_state.GetSpaceReadStateRequest, +): + transport_class = transports.ChatServiceRestTransport -@pytest.mark.parametrize( - "transport_class", - [ - transports.ChatServiceGrpcTransport, - transports.ChatServiceGrpcAsyncIOTransport, - transports.ChatServiceRestTransport, - ], -) -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 = ChatServiceClient.get_transport_class("grpc")( + unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ) - assert transport.kind == "grpc" + ).get_space_read_state._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + # verify required fields with default values are now present -def test_initialize_client_w_grpc(): - client = ChatServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport="grpc" - ) - assert client is not None + jsonified_request["name"] = "name_value" + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get_space_read_state._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" -# This 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_message_empty_call_grpc(): client = ChatServiceClient( 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_message), "__call__") as call: - call.return_value = gc_message.Message() - client.create_message(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = gc_message.CreateMessageRequest() - - assert args[0] == request_msg + # Designate an appropriate value for the returned response. + return_value = space_read_state.SpaceReadState() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_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 -# This 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_messages_empty_call_grpc(): - client = ChatServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) + # Convert return value to protobuf type + return_value = space_read_state.SpaceReadState.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) - # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.list_messages), "__call__") as call: - call.return_value = message.ListMessagesResponse() - client.list_messages(request=None) + response_value._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 stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = message.ListMessagesRequest() + response = client.get_space_read_state(request) - assert args[0] == request_msg + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == 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_memberships_empty_call_grpc(): - client = ChatServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", +def test_get_space_read_state_rest_unset_required_fields(): + transport = transports.ChatServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials ) - # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.list_memberships), "__call__") as call: - call.return_value = membership.ListMembershipsResponse() - client.list_memberships(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = membership.ListMembershipsRequest() - - assert args[0] == request_msg + unset_fields = transport.get_space_read_state._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) -# This 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_membership_empty_call_grpc(): +def test_get_space_read_state_rest_flattened(): client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", + transport="rest", ) - # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.get_membership), "__call__") as call: - call.return_value = membership.Membership() - client.get_membership(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = membership.GetMembershipRequest() - - 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 = space_read_state.SpaceReadState() + # get arguments that satisfy an http rule for this method + sample_request = {"name": "users/sample1/spaces/sample2/spaceReadState"} -# This 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_message_empty_call_grpc(): - client = ChatServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + ) + mock_args.update(sample_request) - # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.get_message), "__call__") as call: - call.return_value = message.Message() - client.get_message(request=None) + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = space_read_state.SpaceReadState.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._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 stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = message.GetMessageRequest() + client.get_space_read_state(**mock_args) - 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=users/*/spaces/*/spaceReadState}" % 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_message_empty_call_grpc(): +def test_get_space_read_state_rest_flattened_error(transport: str = "rest"): client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", + transport=transport, ) - # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.update_message), "__call__") as call: - call.return_value = gc_message.Message() - client.update_message(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = gc_message.UpdateMessageRequest() - - 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_space_read_state( + space_read_state.GetSpaceReadStateRequest(), + 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_message_empty_call_grpc(): - client = ChatServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) +def test_update_space_read_state_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) - # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.delete_message), "__call__") as call: - call.return_value = None - client.delete_message(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 = message.DeleteMessageRequest() + # Ensure method has been cached + assert ( + client._transport.update_space_read_state + in client._transport._wrapped_methods + ) - 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_space_read_state + ] = mock_rpc + request = {} + client.update_space_read_state(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_attachment_empty_call_grpc(): - client = ChatServiceClient( - 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_attachment), "__call__") as call: - call.return_value = attachment.Attachment() - client.get_attachment(request=None) + client.update_space_read_state(request) - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = attachment.GetAttachmentRequest() + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 - assert args[0] == request_msg +def test_update_space_read_state_rest_required_fields( + request_type=gc_space_read_state.UpdateSpaceReadStateRequest, +): + transport_class = transports.ChatServiceRestTransport -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_upload_attachment_empty_call_grpc(): - client = ChatServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", + 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) ) - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.upload_attachment), "__call__" - ) as call: - call.return_value = attachment.UploadAttachmentResponse() - client.upload_attachment(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 = attachment.UploadAttachmentRequest() + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).update_space_read_state._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) - assert args[0] == request_msg + # verify required fields with default values are now present + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).update_space_read_state._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("update_mask",)) + jsonified_request.update(unset_fields) + # 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. -def test_list_spaces_empty_call_grpc(): client = ChatServiceClient( 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_spaces), "__call__") as call: - call.return_value = space.ListSpacesResponse() - client.list_spaces(request=None) + # Designate an appropriate value for the returned response. + return_value = gc_space_read_state.SpaceReadState() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force 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 = space.ListSpacesRequest() + response_value = Response() + response_value.status_code = 200 - assert args[0] == request_msg + # Convert return value to protobuf type + return_value = gc_space_read_state.SpaceReadState.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._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. -def test_search_spaces_empty_call_grpc(): - client = ChatServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) + response = client.update_space_read_state(request) - # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.search_spaces), "__call__") as call: - call.return_value = space.SearchSpacesResponse() - client.search_spaces(request=None) + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = space.SearchSpacesRequest() - assert args[0] == request_msg +def test_update_space_read_state_rest_unset_required_fields(): + transport = transports.ChatServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.update_space_read_state._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(("updateMask",)) + & set( + ( + "spaceReadState", + "updateMask", + ) + ) + ) -# This 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_space_empty_call_grpc(): +def test_update_space_read_state_rest_flattened(): client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", + transport="rest", ) - # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.get_space), "__call__") as call: - call.return_value = space.Space() - client.get_space(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = space.GetSpaceRequest() - - 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 = gc_space_read_state.SpaceReadState() + # get arguments that satisfy an http rule for this method + sample_request = { + "space_read_state": {"name": "users/sample1/spaces/sample2/spaceReadState"} + } -# This 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_space_empty_call_grpc(): - client = ChatServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) + # get truthy value for each flattened field + mock_args = dict( + space_read_state=gc_space_read_state.SpaceReadState(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + mock_args.update(sample_request) - # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.create_space), "__call__") as call: - call.return_value = gc_space.Space() - client.create_space(request=None) + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = gc_space_read_state.SpaceReadState.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._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 stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = gc_space.CreateSpaceRequest() + client.update_space_read_state(**mock_args) - 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/{space_read_state.name=users/*/spaces/*/spaceReadState}" + % 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_set_up_space_empty_call_grpc(): +def test_update_space_read_state_rest_flattened_error(transport: str = "rest"): client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", + transport=transport, ) - # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.set_up_space), "__call__") as call: - call.return_value = space.Space() - client.set_up_space(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = space_setup.SetUpSpaceRequest() - - 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.update_space_read_state( + gc_space_read_state.UpdateSpaceReadStateRequest(), + space_read_state=gc_space_read_state.SpaceReadState(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_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_space_empty_call_grpc(): - client = ChatServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) +def test_get_thread_read_state_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) - # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.update_space), "__call__") as call: - call.return_value = gc_space.Space() - client.update_space(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 = gc_space.UpdateSpaceRequest() + # Ensure method has been cached + assert ( + client._transport.get_thread_read_state + in client._transport._wrapped_methods + ) - 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_thread_read_state] = ( + mock_rpc + ) + request = {} + client.get_thread_read_state(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_space_empty_call_grpc(): - client = ChatServiceClient( - 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_space), "__call__") as call: - call.return_value = None - client.delete_space(request=None) + client.get_thread_read_state(request) - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = space.DeleteSpaceRequest() + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 - assert args[0] == request_msg +def test_get_thread_read_state_rest_required_fields( + request_type=thread_read_state.GetThreadReadStateRequest, +): + transport_class = transports.ChatServiceRestTransport -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_complete_import_space_empty_call_grpc(): - client = ChatServiceClient( - 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.complete_import_space), "__call__" - ) as call: - call.return_value = space.CompleteImportSpaceResponse() - client.complete_import_space(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 = space.CompleteImportSpaceRequest() + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get_thread_read_state._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) - assert args[0] == request_msg + # verify required fields with default values are now present + jsonified_request["name"] = "name_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get_thread_read_state._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_find_direct_message_empty_call_grpc(): client = ChatServiceClient( 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.find_direct_message), "__call__" - ) as call: - call.return_value = space.Space() - client.find_direct_message(request=None) + # Designate an appropriate value for the returned response. + return_value = thread_read_state.ThreadReadState() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_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 = space.FindDirectMessageRequest() + response_value = Response() + response_value.status_code = 200 - assert args[0] == request_msg + # Convert return value to protobuf type + return_value = thread_read_state.ThreadReadState.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._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. -def test_create_membership_empty_call_grpc(): - client = ChatServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) + response = client.get_thread_read_state(request) - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.create_membership), "__call__" - ) as call: - call.return_value = gc_membership.Membership() - client.create_membership(request=None) + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = gc_membership.CreateMembershipRequest() - assert args[0] == request_msg +def test_get_thread_read_state_rest_unset_required_fields(): + transport = transports.ChatServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + unset_fields = transport.get_thread_read_state._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) -# This 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_membership_empty_call_grpc(): + +def test_get_thread_read_state_rest_flattened(): client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", + transport="rest", ) - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.update_membership), "__call__" - ) as call: - call.return_value = gc_membership.Membership() - client.update_membership(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 = thread_read_state.ThreadReadState() - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = gc_membership.UpdateMembershipRequest() + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "users/sample1/spaces/sample2/threads/sample3/threadReadState" + } - assert args[0] == request_msg + # 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 = thread_read_state.ThreadReadState.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = 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_thread_read_state(**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. -def test_delete_membership_empty_call_grpc(): + # Establish that the underlying call was 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=users/*/spaces/*/threads/*/threadReadState}" + % client.transport._host, + args[1], + ) + + +def test_get_thread_read_state_rest_flattened_error(transport: str = "rest"): client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", + transport=transport, ) - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.delete_membership), "__call__" - ) as call: - call.return_value = membership.Membership() - client.delete_membership(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = membership.DeleteMembershipRequest() - - 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_thread_read_state( + thread_read_state.GetThreadReadStateRequest(), + 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_reaction_empty_call_grpc(): - client = ChatServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) +def test_get_space_event_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) - # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.create_reaction), "__call__") as call: - call.return_value = gc_reaction.Reaction() - client.create_reaction(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 = gc_reaction.CreateReactionRequest() + # Ensure method has been cached + assert client._transport.get_space_event in client._transport._wrapped_methods - 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_space_event] = mock_rpc + request = {} + client.get_space_event(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_reactions_empty_call_grpc(): - client = ChatServiceClient( - 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.list_reactions), "__call__") as call: - call.return_value = reaction.ListReactionsResponse() - client.list_reactions(request=None) + client.get_space_event(request) - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = reaction.ListReactionsRequest() + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 - assert args[0] == request_msg +def test_get_space_event_rest_required_fields( + request_type=space_event.GetSpaceEventRequest, +): + transport_class = transports.ChatServiceRestTransport -# This 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_reaction_empty_call_grpc(): - client = ChatServiceClient( - 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.delete_reaction), "__call__") as call: - call.return_value = None - client.delete_reaction(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 = reaction.DeleteReactionRequest() + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get_space_event._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) - assert args[0] == request_msg + # verify required fields with default values are now present + jsonified_request["name"] = "name_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get_space_event._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" -# This 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_custom_emoji_empty_call_grpc(): client = ChatServiceClient( 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_custom_emoji), "__call__" - ) as call: - call.return_value = reaction.CustomEmoji() - client.create_custom_emoji(request=None) + # Designate an appropriate value for the returned response. + return_value = space_event.SpaceEvent() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_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 = reaction.CreateCustomEmojiRequest() + response_value = Response() + response_value.status_code = 200 - assert args[0] == request_msg + # Convert return value to protobuf type + return_value = space_event.SpaceEvent.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._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. -def test_get_custom_emoji_empty_call_grpc(): - client = ChatServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) + response = client.get_space_event(request) - # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.get_custom_emoji), "__call__") as call: - call.return_value = reaction.CustomEmoji() - client.get_custom_emoji(request=None) + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = reaction.GetCustomEmojiRequest() - assert args[0] == request_msg +def test_get_space_event_rest_unset_required_fields(): + transport = transports.ChatServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.get_space_event._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) -# This 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_custom_emojis_empty_call_grpc(): +def test_get_space_event_rest_flattened(): client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", + transport="rest", ) - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_custom_emojis), "__call__" - ) as call: - call.return_value = reaction.ListCustomEmojisResponse() - client.list_custom_emojis(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = reaction.ListCustomEmojisRequest() - - 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 = space_event.SpaceEvent() + # get arguments that satisfy an http rule for this method + sample_request = {"name": "spaces/sample1/spaceEvents/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_custom_emoji_empty_call_grpc(): - client = ChatServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + ) + mock_args.update(sample_request) - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.delete_custom_emoji), "__call__" - ) as call: - call.return_value = None - client.delete_custom_emoji(request=None) + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = space_event.SpaceEvent.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._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 stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = reaction.DeleteCustomEmojiRequest() + client.get_space_event(**mock_args) - 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=spaces/*/spaceEvents/*}" % 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_space_read_state_empty_call_grpc(): +def test_get_space_event_rest_flattened_error(transport: str = "rest"): client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", + transport=transport, ) - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_space_read_state), "__call__" - ) as call: - call.return_value = space_read_state.SpaceReadState() - client.get_space_read_state(request=None) + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_space_event( + space_event.GetSpaceEventRequest(), + name="name_value", + ) - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = space_read_state.GetSpaceReadStateRequest() - assert args[0] == request_msg +def test_list_space_events_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = ChatServiceClient( + 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_update_space_read_state_empty_call_grpc(): - client = ChatServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) + # Ensure method has been cached + assert client._transport.list_space_events in client._transport._wrapped_methods - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.update_space_read_state), "__call__" - ) as call: - call.return_value = gc_space_read_state.SpaceReadState() - client.update_space_read_state(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.list_space_events] = ( + mock_rpc + ) - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = gc_space_read_state.UpdateSpaceReadStateRequest() + request = {} + client.list_space_events(request) - assert args[0] == request_msg + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + client.list_space_events(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_thread_read_state_empty_call_grpc(): - client = ChatServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_thread_read_state), "__call__" - ) as call: - call.return_value = thread_read_state.ThreadReadState() - client.get_thread_read_state(request=None) - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = thread_read_state.GetThreadReadStateRequest() +def test_list_space_events_rest_required_fields( + request_type=space_event.ListSpaceEventsRequest, +): + transport_class = transports.ChatServiceRestTransport - assert args[0] == request_msg + request_init = {} + request_init["parent"] = "" + request_init["filter"] = "" + request = request_type(**request_init) + pb_request = request_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 "filter" 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_get_space_event_empty_call_grpc(): - client = ChatServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).list_space_events._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) - # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.get_space_event), "__call__") as call: - call.return_value = space_event.SpaceEvent() - client.get_space_event(request=None) + # verify required fields with default values are now present + assert "filter" in jsonified_request + assert jsonified_request["filter"] == request_init["filter"] - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = space_event.GetSpaceEventRequest() + jsonified_request["parent"] = "parent_value" + jsonified_request["filter"] = "filter_value" - assert args[0] == request_msg + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).list_space_events._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "filter", + "page_size", + "page_token", + ) + ) + jsonified_request.update(unset_fields) + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + assert "filter" in jsonified_request + assert jsonified_request["filter"] == "filter_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_space_events_empty_call_grpc(): client = ChatServiceClient( 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_space_events), "__call__" - ) as call: - call.return_value = space_event.ListSpaceEventsResponse() - client.list_space_events(request=None) + # Designate an appropriate value for the returned response. + return_value = space_event.ListSpaceEventsResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_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 = space_event.ListSpaceEventsRequest() + response_value = Response() + response_value.status_code = 200 - assert args[0] == request_msg + # Convert return value to protobuf type + return_value = space_event.ListSpaceEventsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._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. -def test_get_space_notification_setting_empty_call_grpc(): - client = ChatServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) + response = client.list_space_events(request) - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_space_notification_setting), "__call__" - ) as call: - call.return_value = space_notification_setting.SpaceNotificationSetting() - client.get_space_notification_setting(request=None) + expected_params = [ + ( + "filter", + "", + ), + ("$alt", "json;enum-encoding=int"), + ] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = space_notification_setting.GetSpaceNotificationSettingRequest() - assert args[0] == request_msg +def test_list_space_events_rest_unset_required_fields(): + transport = transports.ChatServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.list_space_events._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "filter", + "pageSize", + "pageToken", + ) + ) + & set( + ( + "parent", + "filter", + ) + ) + ) -# This 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_space_notification_setting_empty_call_grpc(): +def test_list_space_events_rest_flattened(): client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", + transport="rest", ) - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.update_space_notification_setting), "__call__" - ) as call: - call.return_value = gc_space_notification_setting.SpaceNotificationSetting() - client.update_space_notification_setting(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 = space_event.ListSpaceEventsResponse() - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = ( - gc_space_notification_setting.UpdateSpaceNotificationSettingRequest() + # get arguments that satisfy an http rule for this method + sample_request = {"parent": "spaces/sample1"} + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + filter="filter_value", ) + mock_args.update(sample_request) - 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 = space_event.ListSpaceEventsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = 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_space_events(**mock_args) -def test_transport_kind_grpc_asyncio(): - transport = ChatServiceAsyncClient.get_transport_class("grpc_asyncio")( - credentials=async_anonymous_credentials() - ) - assert transport.kind == "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=spaces/*}/spaceEvents" % client.transport._host, args[1] + ) -def test_initialize_client_w_grpc_asyncio(): - client = ChatServiceAsyncClient( - credentials=async_anonymous_credentials(), transport="grpc_asyncio" +def test_list_space_events_rest_flattened_error(transport: str = "rest"): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, ) - 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_space_events( + space_event.ListSpaceEventsRequest(), + parent="parent_value", + filter="filter_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_message_empty_call_grpc_asyncio(): - client = ChatServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", +def test_list_space_events_rest_pager(transport: str = "rest"): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, ) - # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.create_message), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - gc_message.Message( - name="name_value", - text="text_value", - formatted_text="formatted_text_value", - fallback_text="fallback_text_value", - argument_text="argument_text_value", - thread_reply=True, - client_assigned_message_id="client_assigned_message_id_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 = ( + space_event.ListSpaceEventsResponse( + space_events=[ + space_event.SpaceEvent(), + space_event.SpaceEvent(), + space_event.SpaceEvent(), + ], + next_page_token="abc", + ), + space_event.ListSpaceEventsResponse( + space_events=[], + next_page_token="def", + ), + space_event.ListSpaceEventsResponse( + space_events=[ + space_event.SpaceEvent(), + ], + next_page_token="ghi", + ), + space_event.ListSpaceEventsResponse( + space_events=[ + space_event.SpaceEvent(), + space_event.SpaceEvent(), + ], + ), ) - await client.create_message(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 = gc_message.CreateMessageRequest() + # Wrap the values into proper Response objs + response = tuple( + space_event.ListSpaceEventsResponse.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 - assert args[0] == request_msg + sample_request = {"parent": "spaces/sample1"} + pager = client.list_space_events(request=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_list_messages_empty_call_grpc_asyncio(): - client = ChatServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, space_event.SpaceEvent) for i in results) - # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.list_messages), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - message.ListMessagesResponse( - next_page_token="next_page_token_value", - ) - ) - await client.list_messages(request=None) + pages = list(client.list_space_events(request=sample_request).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = message.ListMessagesRequest() - assert args[0] == request_msg +def test_get_space_notification_setting_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = ChatServiceClient( + 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_list_memberships_empty_call_grpc_asyncio(): - client = ChatServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) + # Ensure method has been cached + assert ( + client._transport.get_space_notification_setting + in client._transport._wrapped_methods + ) - # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.list_memberships), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - membership.ListMembershipsResponse( - 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.list_memberships(request=None) + client._transport._wrapped_methods[ + client._transport.get_space_notification_setting + ] = mock_rpc - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = membership.ListMembershipsRequest() + request = {} + client.get_space_notification_setting(request) - assert args[0] == request_msg + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + client.get_space_notification_setting(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_membership_empty_call_grpc_asyncio(): - client = ChatServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", + # Establish 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_space_notification_setting_rest_required_fields( + request_type=space_notification_setting.GetSpaceNotificationSettingRequest, +): + transport_class = transports.ChatServiceRestTransport + + 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_membership), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - membership.Membership( - name="name_value", - state=membership.Membership.MembershipState.JOINED, - role=membership.Membership.MembershipRole.ROLE_MEMBER, - ) - ) - await client.get_membership(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 = membership.GetMembershipRequest() + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get_space_notification_setting._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) - assert args[0] == request_msg + # verify required fields with default values are now present + 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_get_message_empty_call_grpc_asyncio(): - client = ChatServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get_space_notification_setting._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + + client = ChatServiceClient( + 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_message), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - message.Message( - name="name_value", - text="text_value", - formatted_text="formatted_text_value", - fallback_text="fallback_text_value", - argument_text="argument_text_value", - thread_reply=True, - client_assigned_message_id="client_assigned_message_id_value", - ) - ) - await client.get_message(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = message.GetMessageRequest() + # Designate an appropriate value for the returned response. + return_value = space_notification_setting.SpaceNotificationSetting() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "get", + "query_params": pb_request, + } + transcode.return_value = transcode_result - assert args[0] == request_msg + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = space_notification_setting.SpaceNotificationSetting.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_message_empty_call_grpc_asyncio(): - client = ChatServiceAsyncClient( - 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_message), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - gc_message.Message( - name="name_value", - text="text_value", - formatted_text="formatted_text_value", - fallback_text="fallback_text_value", - argument_text="argument_text_value", - thread_reply=True, - client_assigned_message_id="client_assigned_message_id_value", - ) - ) - await client.update_message(request=None) + response = client.get_space_notification_setting(request) - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = gc_message.UpdateMessageRequest() + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params - assert args[0] == request_msg +def test_get_space_notification_setting_rest_unset_required_fields(): + transport = transports.ChatServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) -# This test is a coverage 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_message_empty_call_grpc_asyncio(): - client = ChatServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", + unset_fields = transport.get_space_notification_setting._get_unset_required_fields( + {} ) + assert set(unset_fields) == (set(()) & set(("name",))) - # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.delete_message), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.delete_message(request=None) - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = message.DeleteMessageRequest() +def test_get_space_notification_setting_rest_flattened(): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) - 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 = space_notification_setting.SpaceNotificationSetting() + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "users/sample1/spaces/sample2/spaceNotificationSetting" + } -# This test is a coverage 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_attachment_empty_call_grpc_asyncio(): - client = ChatServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + ) + mock_args.update(sample_request) - # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.get_attachment), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - attachment.Attachment( - name="name_value", - content_name="content_name_value", - content_type="content_type_value", - thumbnail_uri="thumbnail_uri_value", - download_uri="download_uri_value", - source=attachment.Attachment.Source.DRIVE_FILE, - ) + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = space_notification_setting.SpaceNotificationSetting.pb( + return_value ) - await client.get_attachment(request=None) + json_return_value = json_format.MessageToJson(return_value) + response_value._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 stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = attachment.GetAttachmentRequest() + client.get_space_notification_setting(**mock_args) - 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=users/*/spaces/*/spaceNotificationSetting}" + % 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_upload_attachment_empty_call_grpc_asyncio(): - client = ChatServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", +def test_get_space_notification_setting_rest_flattened_error(transport: str = "rest"): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, ) - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.upload_attachment), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - attachment.UploadAttachmentResponse() + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_space_notification_setting( + space_notification_setting.GetSpaceNotificationSettingRequest(), + name="name_value", ) - await client.upload_attachment(request=None) - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = attachment.UploadAttachmentRequest() - - assert args[0] == request_msg +def test_update_space_notification_setting_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = ChatServiceClient( + 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_list_spaces_empty_call_grpc_asyncio(): - client = ChatServiceAsyncClient( - 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.list_spaces), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - space.ListSpacesResponse( - next_page_token="next_page_token_value", - ) + # Ensure method has been cached + assert ( + client._transport.update_space_notification_setting + in client._transport._wrapped_methods ) - await client.list_spaces(request=None) - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = space.ListSpacesRequest() + # Replace cached wrapped function with mock + mock_rpc = 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_space_notification_setting + ] = mock_rpc - assert args[0] == request_msg + request = {} + client.update_space_notification_setting(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_search_spaces_empty_call_grpc_asyncio(): - client = ChatServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) + client.update_space_notification_setting(request) - # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.search_spaces), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - space.SearchSpacesResponse( - next_page_token="next_page_token_value", - total_size=1086, - ) - ) - await client.search_spaces(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = space.SearchSpacesRequest() + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 - assert args[0] == request_msg +def test_update_space_notification_setting_rest_required_fields( + request_type=gc_space_notification_setting.UpdateSpaceNotificationSettingRequest, +): + transport_class = transports.ChatServiceRestTransport -# This test is a coverage 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_space_empty_call_grpc_asyncio(): - client = ChatServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", + 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) ) - # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.get_space), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - space.Space( - name="name_value", - type_=space.Space.Type.ROOM, - space_type=space.Space.SpaceType.SPACE, - single_user_bot_dm=True, - threaded=True, - display_name="display_name_value", - external_user_allowed=True, - space_threading_state=space.Space.SpaceThreadingState.THREADED_MESSAGES, - space_history_state=history_state.HistoryState.HISTORY_OFF, - import_mode=True, - admin_installed=True, - customer="customer_value", - space_uri="space_uri_value", - ) - ) - await client.get_space(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 = space.GetSpaceRequest() + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).update_space_notification_setting._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) - assert args[0] == request_msg + # verify required fields with default values are now present + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).update_space_notification_setting._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("update_mask",)) + jsonified_request.update(unset_fields) -# This test is a coverage 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_space_empty_call_grpc_asyncio(): - client = ChatServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", + # verify required fields with non-default values are left alone + + client = ChatServiceClient( + 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_space), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - gc_space.Space( - name="name_value", - type_=gc_space.Space.Type.ROOM, - space_type=gc_space.Space.SpaceType.SPACE, - single_user_bot_dm=True, - threaded=True, - display_name="display_name_value", - external_user_allowed=True, - space_threading_state=gc_space.Space.SpaceThreadingState.THREADED_MESSAGES, - space_history_state=history_state.HistoryState.HISTORY_OFF, - import_mode=True, - admin_installed=True, - customer="customer_value", - space_uri="space_uri_value", + # Designate an appropriate value for the returned response. + return_value = gc_space_notification_setting.SpaceNotificationSetting() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force 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 = gc_space_notification_setting.SpaceNotificationSetting.pb( + return_value ) - ) - await client.create_space(request=None) + json_return_value = json_format.MessageToJson(return_value) - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = gc_space.CreateSpaceRequest() + response_value._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 args[0] == request_msg + response = client.update_space_notification_setting(request) + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == 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_set_up_space_empty_call_grpc_asyncio(): - client = ChatServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", + +def test_update_space_notification_setting_rest_unset_required_fields(): + transport = transports.ChatServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials ) - # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.set_up_space), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - space.Space( - name="name_value", - type_=space.Space.Type.ROOM, - space_type=space.Space.SpaceType.SPACE, - single_user_bot_dm=True, - threaded=True, - display_name="display_name_value", - external_user_allowed=True, - space_threading_state=space.Space.SpaceThreadingState.THREADED_MESSAGES, - space_history_state=history_state.HistoryState.HISTORY_OFF, - import_mode=True, - admin_installed=True, - customer="customer_value", - space_uri="space_uri_value", + unset_fields = ( + transport.update_space_notification_setting._get_unset_required_fields({}) + ) + assert set(unset_fields) == ( + set(("updateMask",)) + & set( + ( + "spaceNotificationSetting", + "updateMask", ) ) - await client.set_up_space(request=None) + ) - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = space_setup.SetUpSpaceRequest() - assert args[0] == request_msg +def test_update_space_notification_setting_rest_flattened(): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = gc_space_notification_setting.SpaceNotificationSetting() -# This test is a coverage 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_space_empty_call_grpc_asyncio(): - client = ChatServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) + # get arguments that satisfy an http rule for this method + sample_request = { + "space_notification_setting": { + "name": "users/sample1/spaces/sample2/spaceNotificationSetting" + } + } - # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.update_space), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - gc_space.Space( - name="name_value", - type_=gc_space.Space.Type.ROOM, - space_type=gc_space.Space.SpaceType.SPACE, - single_user_bot_dm=True, - threaded=True, - display_name="display_name_value", - external_user_allowed=True, - space_threading_state=gc_space.Space.SpaceThreadingState.THREADED_MESSAGES, - space_history_state=history_state.HistoryState.HISTORY_OFF, - import_mode=True, - admin_installed=True, - customer="customer_value", - space_uri="space_uri_value", - ) + # get truthy value for each flattened field + mock_args = dict( + space_notification_setting=gc_space_notification_setting.SpaceNotificationSetting( + name="name_value" + ), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) - await client.update_space(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = gc_space.UpdateSpaceRequest() + mock_args.update(sample_request) - 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 = gc_space_notification_setting.SpaceNotificationSetting.pb( + return_value + ) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = 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_space_notification_setting(**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_delete_space_empty_call_grpc_asyncio(): - client = ChatServiceAsyncClient( - 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/{space_notification_setting.name=users/*/spaces/*/spaceNotificationSetting}" + % client.transport._host, + args[1], + ) + + +def test_update_space_notification_setting_rest_flattened_error( + transport: str = "rest", +): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, ) - # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.delete_space), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.delete_space(request=None) + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.update_space_notification_setting( + gc_space_notification_setting.UpdateSpaceNotificationSettingRequest(), + space_notification_setting=gc_space_notification_setting.SpaceNotificationSetting( + name="name_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 = space.DeleteSpaceRequest() - assert args[0] == request_msg +def test_create_section_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = ChatServiceClient( + 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_complete_import_space_empty_call_grpc_asyncio(): - client = ChatServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) + # Ensure method has been cached + assert client._transport.create_section in client._transport._wrapped_methods - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.complete_import_space), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - space.CompleteImportSpaceResponse() + # Replace cached 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.complete_import_space(request=None) + client._transport._wrapped_methods[client._transport.create_section] = mock_rpc - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = space.CompleteImportSpaceRequest() + request = {} + client.create_section(request) - assert args[0] == request_msg + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + client.create_section(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_find_direct_message_empty_call_grpc_asyncio(): - client = ChatServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.find_direct_message), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - space.Space( - name="name_value", - type_=space.Space.Type.ROOM, - space_type=space.Space.SpaceType.SPACE, - single_user_bot_dm=True, - threaded=True, - display_name="display_name_value", - external_user_allowed=True, - space_threading_state=space.Space.SpaceThreadingState.THREADED_MESSAGES, - space_history_state=history_state.HistoryState.HISTORY_OFF, - import_mode=True, - admin_installed=True, - customer="customer_value", - space_uri="space_uri_value", - ) - ) - await client.find_direct_message(request=None) - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = space.FindDirectMessageRequest() +def test_create_section_rest_required_fields( + request_type=gc_section.CreateSectionRequest, +): + transport_class = transports.ChatServiceRestTransport - assert args[0] == request_msg + 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 -# This test is a coverage 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_membership_empty_call_grpc_asyncio(): - client = ChatServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).create_section._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.create_membership), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - gc_membership.Membership( - name="name_value", - state=gc_membership.Membership.MembershipState.JOINED, - role=gc_membership.Membership.MembershipRole.ROLE_MEMBER, - ) - ) - await client.create_membership(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 = gc_membership.CreateMembershipRequest() + jsonified_request["parent"] = "parent_value" - assert args[0] == request_msg + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).create_section._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" -# This test is a coverage 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_membership_empty_call_grpc_asyncio(): - client = ChatServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", + client = ChatServiceClient( + 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.update_membership), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - gc_membership.Membership( - name="name_value", - state=gc_membership.Membership.MembershipState.JOINED, - role=gc_membership.Membership.MembershipRole.ROLE_MEMBER, - ) - ) - await client.update_membership(request=None) + # Designate an appropriate value for the returned response. + return_value = gc_section.Section() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force 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 = gc_membership.UpdateMembershipRequest() + response_value = Response() + response_value.status_code = 200 - assert args[0] == request_msg + # Convert return value to protobuf type + return_value = gc_section.Section.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._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_membership_empty_call_grpc_asyncio(): - client = ChatServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", + response = client.create_section(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_create_section_rest_unset_required_fields(): + transport = transports.ChatServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials ) - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.delete_membership), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - membership.Membership( - name="name_value", - state=membership.Membership.MembershipState.JOINED, - role=membership.Membership.MembershipRole.ROLE_MEMBER, + unset_fields = transport.create_section._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(()) + & set( + ( + "parent", + "section", ) ) - await client.delete_membership(request=None) + ) - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = membership.DeleteMembershipRequest() - assert args[0] == request_msg +def test_create_section_rest_flattened(): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = gc_section.Section() -# This test is a coverage 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_reaction_empty_call_grpc_asyncio(): - client = ChatServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) + # get arguments that satisfy an http rule for this method + sample_request = {"parent": "users/sample1"} - # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.create_reaction), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - gc_reaction.Reaction( - name="name_value", - ) + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + section=gc_section.Section(name="name_value"), ) - await client.create_reaction(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 = gc_reaction.CreateReactionRequest() + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = gc_section.Section.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._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 args[0] == request_msg + client.create_section(**mock_args) + + # Establish that the underlying call was 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=users/*}/sections" % 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_reactions_empty_call_grpc_asyncio(): - client = ChatServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", +def test_create_section_rest_flattened_error(transport: str = "rest"): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, ) - # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.list_reactions), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - reaction.ListReactionsResponse( - 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_section( + gc_section.CreateSectionRequest(), + parent="parent_value", + section=gc_section.Section(name="name_value"), ) - await client.list_reactions(request=None) - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = reaction.ListReactionsRequest() - assert args[0] == request_msg +def test_delete_section_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = ChatServiceClient( + 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_reaction_empty_call_grpc_asyncio(): - client = ChatServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) + # Ensure method has been cached + assert client._transport.delete_section in client._transport._wrapped_methods - # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.delete_reaction), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.delete_reaction(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.delete_section] = mock_rpc - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = reaction.DeleteReactionRequest() + request = {} + client.delete_section(request) - assert args[0] == request_msg + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + client.delete_section(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_custom_emoji_empty_call_grpc_asyncio(): - client = ChatServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.create_custom_emoji), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - reaction.CustomEmoji( - name="name_value", - uid="uid_value", - emoji_name="emoji_name_value", - temporary_image_uri="temporary_image_uri_value", - ) - ) - await client.create_custom_emoji(request=None) - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = reaction.CreateCustomEmojiRequest() +def test_delete_section_rest_required_fields(request_type=section.DeleteSectionRequest): + transport_class = transports.ChatServiceRestTransport - 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_get_custom_emoji_empty_call_grpc_asyncio(): - client = ChatServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).delete_section._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) - # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.get_custom_emoji), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - reaction.CustomEmoji( - name="name_value", - uid="uid_value", - emoji_name="emoji_name_value", - temporary_image_uri="temporary_image_uri_value", - ) - ) - await client.get_custom_emoji(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 = reaction.GetCustomEmojiRequest() + jsonified_request["name"] = "name_value" - assert args[0] == request_msg + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).delete_section._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" -# This test is a coverage 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_custom_emojis_empty_call_grpc_asyncio(): - client = ChatServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", + client = ChatServiceClient( + 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_custom_emojis), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - reaction.ListCustomEmojisResponse( - next_page_token="next_page_token_value", - ) - ) - await client.list_custom_emojis(request=None) + # 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 - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = reaction.ListCustomEmojisRequest() + response_value = Response() + response_value.status_code = 200 + json_return_value = "" - assert args[0] == request_msg + response_value._content = json_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_section(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_delete_custom_emoji_empty_call_grpc_asyncio(): - client = ChatServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_delete_section_rest_unset_required_fields(): + transport = transports.ChatServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials ) - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.delete_custom_emoji), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.delete_custom_emoji(request=None) + unset_fields = transport.delete_section._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = reaction.DeleteCustomEmojiRequest() - assert args[0] == request_msg +def test_delete_section_rest_flattened(): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + # Mock the http request call within the method and 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 -# This test is a coverage 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_space_read_state_empty_call_grpc_asyncio(): - client = ChatServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) + # get arguments that satisfy an http rule for this method + sample_request = {"name": "users/sample1/sections/sample2"} - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_space_read_state), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - space_read_state.SpaceReadState( - name="name_value", - ) + # get truthy value for each flattened field + mock_args = dict( + name="name_value", ) - await client.get_space_read_state(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 = space_read_state.GetSpaceReadStateRequest() + # 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"} - assert args[0] == request_msg + client.delete_section(**mock_args) + # Establish that the underlying call was 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=users/*/sections/*}" % 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_space_read_state_empty_call_grpc_asyncio(): - client = ChatServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", + +def test_delete_section_rest_flattened_error(transport: str = "rest"): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, ) - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.update_space_read_state), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - gc_space_read_state.SpaceReadState( - name="name_value", - ) + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.delete_section( + section.DeleteSectionRequest(), + name="name_value", ) - await client.update_space_read_state(request=None) - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = gc_space_read_state.UpdateSpaceReadStateRequest() - assert args[0] == request_msg +def test_update_section_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = ChatServiceClient( + 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_get_thread_read_state_empty_call_grpc_asyncio(): - client = ChatServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) + # Ensure method has been cached + assert client._transport.update_section in client._transport._wrapped_methods - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_thread_read_state), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - thread_read_state.ThreadReadState( - name="name_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.get_thread_read_state(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = thread_read_state.GetThreadReadStateRequest() - - assert args[0] == request_msg + client._transport._wrapped_methods[client._transport.update_section] = mock_rpc + request = {} + client.update_section(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_space_event_empty_call_grpc_asyncio(): - client = ChatServiceAsyncClient( - 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_space_event), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - space_event.SpaceEvent( - name="name_value", - event_type="event_type_value", - ) - ) - await client.get_space_event(request=None) + client.update_section(request) - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = space_event.GetSpaceEventRequest() + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 - assert args[0] == request_msg +def test_update_section_rest_required_fields( + request_type=gc_section.UpdateSectionRequest, +): + transport_class = transports.ChatServiceRestTransport -# This test is a coverage 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_space_events_empty_call_grpc_asyncio(): - client = ChatServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", + 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) ) - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_space_events), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - space_event.ListSpaceEventsResponse( - next_page_token="next_page_token_value", - ) - ) - await client.list_space_events(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 = space_event.ListSpaceEventsRequest() + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).update_section._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) - assert args[0] == request_msg + # verify required fields with default values are now present + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).update_section._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("update_mask",)) + jsonified_request.update(unset_fields) -# This test is a coverage 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_space_notification_setting_empty_call_grpc_asyncio(): - client = ChatServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", + # verify required fields with non-default values are left alone + + client = ChatServiceClient( + 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_space_notification_setting), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - space_notification_setting.SpaceNotificationSetting( - name="name_value", - notification_setting=space_notification_setting.SpaceNotificationSetting.NotificationSetting.ALL, - mute_setting=space_notification_setting.SpaceNotificationSetting.MuteSetting.UNMUTED, - ) - ) - await client.get_space_notification_setting(request=None) + # Designate an appropriate value for the returned response. + return_value = gc_section.Section() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force 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 = space_notification_setting.GetSpaceNotificationSettingRequest() + response_value = Response() + response_value.status_code = 200 - assert args[0] == request_msg + # Convert return value to protobuf type + return_value = gc_section.Section.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._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_update_space_notification_setting_empty_call_grpc_asyncio(): - client = ChatServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", + response = client.update_section(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_update_section_rest_unset_required_fields(): + transport = transports.ChatServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials ) - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.update_space_notification_setting), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - gc_space_notification_setting.SpaceNotificationSetting( - name="name_value", - notification_setting=gc_space_notification_setting.SpaceNotificationSetting.NotificationSetting.ALL, - mute_setting=gc_space_notification_setting.SpaceNotificationSetting.MuteSetting.UNMUTED, + unset_fields = transport.update_section._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(("updateMask",)) + & set( + ( + "section", + "updateMask", ) ) - await client.update_space_notification_setting(request=None) + ) - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = ( - gc_space_notification_setting.UpdateSpaceNotificationSettingRequest() + +def test_update_section_rest_flattened(): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = gc_section.Section() + + # get arguments that satisfy an http rule for this method + sample_request = {"section": {"name": "users/sample1/sections/sample2"}} + + # get truthy value for each flattened field + mock_args = dict( + section=gc_section.Section(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) + mock_args.update(sample_request) - 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 = gc_section.Section.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = 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_section(**mock_args) -def test_transport_kind_rest(): - transport = ChatServiceClient.get_transport_class("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/{section.name=users/*/sections/*}" % client.transport._host, args[1] + ) + + +def test_update_section_rest_flattened_error(transport: str = "rest"): + client = ChatServiceClient( + credentials=ga_credentials.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_section( + gc_section.UpdateSectionRequest(), + section=gc_section.Section(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +def test_list_sections_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should 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_sections in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_sections] = mock_rpc + + request = {} + client.list_sections(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_sections(request) + + # Establish 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_sections_rest_required_fields(request_type=section.ListSectionsRequest): + transport_class = transports.ChatServiceRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).list_sections._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = "parent_value" + + unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() + ).list_sections._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "page_size", + "page_token", + ) ) - assert transport.kind == "rest" + jsonified_request.update(unset_fields) + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" -def test_create_message_rest_bad_request(request_type=gc_message.CreateMessageRequest): client = ChatServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - # send a request that will satisfy transcoding - request_init = {"parent": "spaces/sample1"} request = request_type(**request_init) - # Mock the http request call within the method and fake a BadRequest error. - with ( - mock.patch.object(Session, "request") as req, - pytest.raises(core_exceptions.BadRequest), - ): + # Designate an appropriate value for the returned response. + return_value = section.ListSectionsResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_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 = section.ListSectionsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_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_sections(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_list_sections_rest_unset_required_fields(): + transport = transports.ChatServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.list_sections._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "pageSize", + "pageToken", + ) + ) + & set(("parent",)) + ) + + +def test_list_sections_rest_flattened(): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = section.ListSectionsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {"parent": "users/sample1"} + + # 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 = mock.Mock() - json_return_value = "" - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = mock.Mock() + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = section.ListSectionsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = 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_message(request) + client.list_sections(**mock_args) -@pytest.mark.parametrize( - "request_type", - [ - gc_message.CreateMessageRequest, - dict, - ], -) -def test_create_message_rest_call_success(request_type): + # Establish that the underlying call was 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=users/*}/sections" % client.transport._host, args[1] + ) + + +def test_list_sections_rest_flattened_error(transport: str = "rest"): client = ChatServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, ) - # send a request that will satisfy transcoding - request_init = {"parent": "spaces/sample1"} - request_init["message"] = { - "name": "name_value", - "sender": { - "name": "name_value", - "display_name": "display_name_value", - "domain_id": "domain_id_value", - "type_": 1, - "is_anonymous": True, - }, - "create_time": {"seconds": 751, "nanos": 543}, - "last_update_time": {}, - "delete_time": {}, - "text": "text_value", - "formatted_text": "formatted_text_value", - "cards": [ - { - "header": { - "title": "title_value", - "subtitle": "subtitle_value", - "image_style": 1, - "image_url": "image_url_value", - }, - "sections": [ - { - "header": "header_value", - "widgets": [ - { - "text_paragraph": {"text": "text_value"}, - "image": { - "image_url": "image_url_value", - "on_click": { - "action": { - "action_method_name": "action_method_name_value", - "parameters": [ - { - "key": "key_value", - "value": "value_value", - } - ], - }, - "open_link": {"url": "url_value"}, - }, - "aspect_ratio": 0.1278, - }, - "key_value": { - "icon": 1, - "icon_url": "icon_url_value", - "top_label": "top_label_value", - "content": "content_value", - "content_multiline": True, - "bottom_label": "bottom_label_value", - "on_click": {}, - "button": { - "text_button": { - "text": "text_value", - "on_click": {}, - }, - "image_button": { - "icon": 1, - "icon_url": "icon_url_value", - "on_click": {}, - "name": "name_value", - }, - }, - }, - "buttons": {}, - } - ], - } + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_sections( + section.ListSectionsRequest(), + parent="parent_value", + ) + + +def test_list_sections_rest_pager(transport: str = "rest"): + client = ChatServiceClient( + 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 = ( + section.ListSectionsResponse( + sections=[ + section.Section(), + section.Section(), + section.Section(), ], - "card_actions": [ - {"action_label": "action_label_value", "on_click": {}} + next_page_token="abc", + ), + section.ListSectionsResponse( + sections=[], + next_page_token="def", + ), + section.ListSectionsResponse( + sections=[ + section.Section(), ], - "name": "name_value", + next_page_token="ghi", + ), + section.ListSectionsResponse( + sections=[ + section.Section(), + section.Section(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(section.ListSectionsResponse.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": "users/sample1"} + + pager = client.list_sections(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, section.Section) for i in results) + + pages = list(client.list_sections(request=sample_request).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +def test_position_section_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.position_section in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.position_section] = ( + mock_rpc + ) + + request = {} + client.position_section(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.position_section(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_position_section_rest_required_fields( + request_type=section.PositionSectionRequest, +): + transport_class = transports.ChatServiceRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).position_section._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).position_section._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = section.PositionSectionResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force 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, } - ], - "cards_v2": [ - { - "card_id": "card_id_value", - "card": { - "header": { - "title": "title_value", - "subtitle": "subtitle_value", - "image_type": 1, - "image_url": "image_url_value", - "image_alt_text": "image_alt_text_value", - }, - "sections": [ - { - "header": "header_value", - "widgets": [ - { - "text_paragraph": { - "text": "text_value", - "max_lines": 960, - "text_syntax": 1, - }, - "image": { - "image_url": "image_url_value", - "on_click": { - "action": { - "function": "function_value", - "parameters": [ - { - "key": "key_value", - "value": "value_value", - } - ], - "load_indicator": 1, - "persist_values": True, - "interaction": 1, - "required_widgets": [ - "required_widgets_value1", - "required_widgets_value2", - ], - "all_widgets_are_required": True, - }, - "open_link": { - "url": "url_value", - "open_as": 1, - "on_close": 1, - }, - "open_dynamic_link_action": {}, - "card": {}, - "overflow_menu": { - "items": [ - { - "start_icon": { - "known_icon": "known_icon_value", - "icon_url": "icon_url_value", - "material_icon": { - "name": "name_value", - "fill": True, - "weight": 648, + 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 = section.PositionSectionResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.position_section(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_position_section_rest_unset_required_fields(): + transport = transports.ChatServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.position_section._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) + + +def test_list_section_items_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should 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_section_items in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = 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_section_items] = ( + mock_rpc + ) + + request = {} + client.list_section_items(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_section_items(request) + + # Establish 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_section_items_rest_required_fields( + request_type=section.ListSectionItemsRequest, +): + transport_class = transports.ChatServiceRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).list_section_items._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = "parent_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).list_section_items._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "filter", + "page_size", + "page_token", + ) + ) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = section.ListSectionItemsResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_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 = section.ListSectionItemsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_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_section_items(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_list_section_items_rest_unset_required_fields(): + transport = transports.ChatServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.list_section_items._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "filter", + "pageSize", + "pageToken", + ) + ) + & set(("parent",)) + ) + + +def test_list_section_items_rest_flattened(): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = section.ListSectionItemsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {"parent": "users/sample1/sections/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 = section.ListSectionItemsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = 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_section_items(**mock_args) + + # Establish that the underlying call was 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=users/*/sections/*}/items" % client.transport._host, args[1] + ) + + +def test_list_section_items_rest_flattened_error(transport: str = "rest"): + client = ChatServiceClient( + credentials=ga_credentials.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_section_items( + section.ListSectionItemsRequest(), + parent="parent_value", + ) + + +def test_list_section_items_rest_pager(transport: str = "rest"): + client = ChatServiceClient( + 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 = ( + section.ListSectionItemsResponse( + section_items=[ + section.SectionItem(), + section.SectionItem(), + section.SectionItem(), + ], + next_page_token="abc", + ), + section.ListSectionItemsResponse( + section_items=[], + next_page_token="def", + ), + section.ListSectionItemsResponse( + section_items=[ + section.SectionItem(), + ], + next_page_token="ghi", + ), + section.ListSectionItemsResponse( + section_items=[ + section.SectionItem(), + section.SectionItem(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(section.ListSectionItemsResponse.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": "users/sample1/sections/sample2"} + + pager = client.list_section_items(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, section.SectionItem) for i in results) + + pages = list(client.list_section_items(request=sample_request).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +def test_move_section_item_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.move_section_item in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.move_section_item] = ( + mock_rpc + ) + + request = {} + client.move_section_item(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.move_section_item(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_move_section_item_rest_required_fields( + request_type=section.MoveSectionItemRequest, +): + transport_class = transports.ChatServiceRestTransport + + request_init = {} + request_init["name"] = "" + request_init["target_section"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).move_section_item._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + jsonified_request["targetSection"] = "target_section_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).move_section_item._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + assert "targetSection" in jsonified_request + assert jsonified_request["targetSection"] == "target_section_value" + + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = section.MoveSectionItemResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force 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 = section.MoveSectionItemResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.move_section_item(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_move_section_item_rest_unset_required_fields(): + transport = transports.ChatServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.move_section_item._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(()) + & set( + ( + "name", + "targetSection", + ) + ) + ) + + +def test_move_section_item_rest_flattened(): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = section.MoveSectionItemResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {"name": "users/sample1/sections/sample2/items/sample3"} + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + target_section="target_section_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = section.MoveSectionItemResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.move_section_item(**mock_args) + + # Establish that the underlying call was 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=users/*/sections/*/items/*}:move" % client.transport._host, + args[1], + ) + + +def test_move_section_item_rest_flattened_error(transport: str = "rest"): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.move_section_item( + section.MoveSectionItemRequest(), + name="name_value", + target_section="target_section_value", + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.ChatServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.ChatServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = ChatServiceClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.ChatServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = ChatServiceClient( + 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 = ChatServiceClient( + client_options=options, credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.ChatServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = ChatServiceClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.ChatServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = ChatServiceClient(transport=transport) + assert client.transport is transport + + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.ChatServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.ChatServiceGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.ChatServiceGrpcTransport, + transports.ChatServiceGrpcAsyncIOTransport, + transports.ChatServiceRestTransport, + ], +) +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 = ChatServiceClient.get_transport_class("grpc")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "grpc" + + +def test_initialize_client_w_grpc(): + client = ChatServiceClient( + 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_message_empty_call_grpc(): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.create_message), "__call__") as call: + call.return_value = gc_message.Message() + client.create_message(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = gc_message.CreateMessageRequest() + + assert args[0] == request_msg + + +# This 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_messages_empty_call_grpc(): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.list_messages), "__call__") as call: + call.return_value = message.ListMessagesResponse() + client.list_messages(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = message.ListMessagesRequest() + + assert args[0] == request_msg + + +# This 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_memberships_empty_call_grpc(): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.list_memberships), "__call__") as call: + call.return_value = membership.ListMembershipsResponse() + client.list_memberships(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = membership.ListMembershipsRequest() + + assert args[0] == request_msg + + +# This 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_membership_empty_call_grpc(): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_membership), "__call__") as call: + call.return_value = membership.Membership() + client.get_membership(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = membership.GetMembershipRequest() + + assert args[0] == request_msg + + +# This 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_message_empty_call_grpc(): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_message), "__call__") as call: + call.return_value = message.Message() + client.get_message(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = message.GetMessageRequest() + + assert args[0] == request_msg + + +# This 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_message_empty_call_grpc(): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.update_message), "__call__") as call: + call.return_value = gc_message.Message() + client.update_message(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = gc_message.UpdateMessageRequest() + + assert args[0] == request_msg + + +# This 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_message_empty_call_grpc(): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.delete_message), "__call__") as call: + call.return_value = None + client.delete_message(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = message.DeleteMessageRequest() + + assert args[0] == request_msg + + +# This 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_attachment_empty_call_grpc(): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_attachment), "__call__") as call: + call.return_value = attachment.Attachment() + client.get_attachment(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = attachment.GetAttachmentRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_upload_attachment_empty_call_grpc(): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.upload_attachment), "__call__" + ) as call: + call.return_value = attachment.UploadAttachmentResponse() + client.upload_attachment(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = attachment.UploadAttachmentRequest() + + assert args[0] == request_msg + + +# This 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_spaces_empty_call_grpc(): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.list_spaces), "__call__") as call: + call.return_value = space.ListSpacesResponse() + client.list_spaces(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = space.ListSpacesRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_search_spaces_empty_call_grpc(): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.search_spaces), "__call__") as call: + call.return_value = space.SearchSpacesResponse() + client.search_spaces(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = space.SearchSpacesRequest() + + assert args[0] == request_msg + + +# This 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_space_empty_call_grpc(): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_space), "__call__") as call: + call.return_value = space.Space() + client.get_space(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = space.GetSpaceRequest() + + assert args[0] == request_msg + + +# This 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_space_empty_call_grpc(): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.create_space), "__call__") as call: + call.return_value = gc_space.Space() + client.create_space(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = gc_space.CreateSpaceRequest() + + assert args[0] == request_msg + + +# This 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_space_empty_call_grpc(): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.set_up_space), "__call__") as call: + call.return_value = space.Space() + client.set_up_space(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = space_setup.SetUpSpaceRequest() + + assert args[0] == request_msg + + +# This 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_space_empty_call_grpc(): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.update_space), "__call__") as call: + call.return_value = gc_space.Space() + client.update_space(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = gc_space.UpdateSpaceRequest() + + assert args[0] == request_msg + + +# This 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_space_empty_call_grpc(): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.delete_space), "__call__") as call: + call.return_value = None + client.delete_space(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = space.DeleteSpaceRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_complete_import_space_empty_call_grpc(): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.complete_import_space), "__call__" + ) as call: + call.return_value = space.CompleteImportSpaceResponse() + client.complete_import_space(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = space.CompleteImportSpaceRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_find_direct_message_empty_call_grpc(): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.find_direct_message), "__call__" + ) as call: + call.return_value = space.Space() + client.find_direct_message(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = space.FindDirectMessageRequest() + + assert args[0] == request_msg + + +# This 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_membership_empty_call_grpc(): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_membership), "__call__" + ) as call: + call.return_value = gc_membership.Membership() + client.create_membership(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = gc_membership.CreateMembershipRequest() + + assert args[0] == request_msg + + +# This 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_membership_empty_call_grpc(): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_membership), "__call__" + ) as call: + call.return_value = gc_membership.Membership() + client.update_membership(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = gc_membership.UpdateMembershipRequest() + + assert args[0] == request_msg + + +# This 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_membership_empty_call_grpc(): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_membership), "__call__" + ) as call: + call.return_value = membership.Membership() + client.delete_membership(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = membership.DeleteMembershipRequest() + + assert args[0] == request_msg + + +# This 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_reaction_empty_call_grpc(): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.create_reaction), "__call__") as call: + call.return_value = gc_reaction.Reaction() + client.create_reaction(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = gc_reaction.CreateReactionRequest() + + assert args[0] == request_msg + + +# This 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_reactions_empty_call_grpc(): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.list_reactions), "__call__") as call: + call.return_value = reaction.ListReactionsResponse() + client.list_reactions(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = reaction.ListReactionsRequest() + + assert args[0] == request_msg + + +# This 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_reaction_empty_call_grpc(): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.delete_reaction), "__call__") as call: + call.return_value = None + client.delete_reaction(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = reaction.DeleteReactionRequest() + + assert args[0] == request_msg + + +# This 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_custom_emoji_empty_call_grpc(): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_custom_emoji), "__call__" + ) as call: + call.return_value = reaction.CustomEmoji() + client.create_custom_emoji(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = reaction.CreateCustomEmojiRequest() + + assert args[0] == request_msg + + +# This 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_custom_emoji_empty_call_grpc(): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_custom_emoji), "__call__") as call: + call.return_value = reaction.CustomEmoji() + client.get_custom_emoji(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = reaction.GetCustomEmojiRequest() + + assert args[0] == request_msg + + +# This 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_custom_emojis_empty_call_grpc(): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_custom_emojis), "__call__" + ) as call: + call.return_value = reaction.ListCustomEmojisResponse() + client.list_custom_emojis(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = reaction.ListCustomEmojisRequest() + + assert args[0] == request_msg + + +# This 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_custom_emoji_empty_call_grpc(): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_custom_emoji), "__call__" + ) as call: + call.return_value = None + client.delete_custom_emoji(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = reaction.DeleteCustomEmojiRequest() + + assert args[0] == request_msg + + +# This 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_space_read_state_empty_call_grpc(): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_space_read_state), "__call__" + ) as call: + call.return_value = space_read_state.SpaceReadState() + client.get_space_read_state(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = space_read_state.GetSpaceReadStateRequest() + + assert args[0] == request_msg + + +# This 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_space_read_state_empty_call_grpc(): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_space_read_state), "__call__" + ) as call: + call.return_value = gc_space_read_state.SpaceReadState() + client.update_space_read_state(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = gc_space_read_state.UpdateSpaceReadStateRequest() + + assert args[0] == request_msg + + +# This 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_thread_read_state_empty_call_grpc(): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_thread_read_state), "__call__" + ) as call: + call.return_value = thread_read_state.ThreadReadState() + client.get_thread_read_state(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = thread_read_state.GetThreadReadStateRequest() + + assert args[0] == request_msg + + +# This 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_space_event_empty_call_grpc(): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_space_event), "__call__") as call: + call.return_value = space_event.SpaceEvent() + client.get_space_event(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = space_event.GetSpaceEventRequest() + + assert args[0] == request_msg + + +# This 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_space_events_empty_call_grpc(): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_space_events), "__call__" + ) as call: + call.return_value = space_event.ListSpaceEventsResponse() + client.list_space_events(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = space_event.ListSpaceEventsRequest() + + assert args[0] == request_msg + + +# This 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_space_notification_setting_empty_call_grpc(): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_space_notification_setting), "__call__" + ) as call: + call.return_value = space_notification_setting.SpaceNotificationSetting() + client.get_space_notification_setting(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = space_notification_setting.GetSpaceNotificationSettingRequest() + + assert args[0] == request_msg + + +# This 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_space_notification_setting_empty_call_grpc(): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_space_notification_setting), "__call__" + ) as call: + call.return_value = gc_space_notification_setting.SpaceNotificationSetting() + client.update_space_notification_setting(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = ( + gc_space_notification_setting.UpdateSpaceNotificationSettingRequest() + ) + + assert args[0] == request_msg + + +# This 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_section_empty_call_grpc(): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.create_section), "__call__") as call: + call.return_value = gc_section.Section() + client.create_section(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = gc_section.CreateSectionRequest() + + assert args[0] == request_msg + + +# This 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_section_empty_call_grpc(): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.delete_section), "__call__") as call: + call.return_value = None + client.delete_section(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = section.DeleteSectionRequest() + + assert args[0] == request_msg + + +# This 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_section_empty_call_grpc(): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.update_section), "__call__") as call: + call.return_value = gc_section.Section() + client.update_section(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = gc_section.UpdateSectionRequest() + + assert args[0] == request_msg + + +# This 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_sections_empty_call_grpc(): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.list_sections), "__call__") as call: + call.return_value = section.ListSectionsResponse() + client.list_sections(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = section.ListSectionsRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_position_section_empty_call_grpc(): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.position_section), "__call__") as call: + call.return_value = section.PositionSectionResponse() + client.position_section(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = section.PositionSectionRequest() + + assert args[0] == request_msg + + +# This 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_section_items_empty_call_grpc(): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_section_items), "__call__" + ) as call: + call.return_value = section.ListSectionItemsResponse() + client.list_section_items(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = section.ListSectionItemsRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_move_section_item_empty_call_grpc(): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.move_section_item), "__call__" + ) as call: + call.return_value = section.MoveSectionItemResponse() + client.move_section_item(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = section.MoveSectionItemRequest() + + assert args[0] == request_msg + + +def test_transport_kind_grpc_asyncio(): + transport = ChatServiceAsyncClient.get_transport_class("grpc_asyncio")( + credentials=async_anonymous_credentials() + ) + assert transport.kind == "grpc_asyncio" + + +def test_initialize_client_w_grpc_asyncio(): + client = ChatServiceAsyncClient( + 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_message_empty_call_grpc_asyncio(): + client = ChatServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.create_message), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gc_message.Message( + name="name_value", + text="text_value", + formatted_text="formatted_text_value", + fallback_text="fallback_text_value", + argument_text="argument_text_value", + thread_reply=True, + client_assigned_message_id="client_assigned_message_id_value", + ) + ) + await client.create_message(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = gc_message.CreateMessageRequest() + + assert args[0] == request_msg + + +# This test is a coverage 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_messages_empty_call_grpc_asyncio(): + client = ChatServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.list_messages), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + message.ListMessagesResponse( + next_page_token="next_page_token_value", + ) + ) + await client.list_messages(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = message.ListMessagesRequest() + + assert args[0] == request_msg + + +# This test is a coverage 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_memberships_empty_call_grpc_asyncio(): + client = ChatServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.list_memberships), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + membership.ListMembershipsResponse( + next_page_token="next_page_token_value", + ) + ) + await client.list_memberships(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = membership.ListMembershipsRequest() + + assert args[0] == request_msg + + +# This test is a coverage 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_membership_empty_call_grpc_asyncio(): + client = ChatServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_membership), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + membership.Membership( + name="name_value", + state=membership.Membership.MembershipState.JOINED, + role=membership.Membership.MembershipRole.ROLE_MEMBER, + ) + ) + await client.get_membership(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = membership.GetMembershipRequest() + + assert args[0] == request_msg + + +# This test is a coverage 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_message_empty_call_grpc_asyncio(): + client = ChatServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_message), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + message.Message( + name="name_value", + text="text_value", + formatted_text="formatted_text_value", + fallback_text="fallback_text_value", + argument_text="argument_text_value", + thread_reply=True, + client_assigned_message_id="client_assigned_message_id_value", + ) + ) + await client.get_message(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = message.GetMessageRequest() + + assert args[0] == request_msg + + +# This test is a coverage 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_message_empty_call_grpc_asyncio(): + client = ChatServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.update_message), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gc_message.Message( + name="name_value", + text="text_value", + formatted_text="formatted_text_value", + fallback_text="fallback_text_value", + argument_text="argument_text_value", + thread_reply=True, + client_assigned_message_id="client_assigned_message_id_value", + ) + ) + await client.update_message(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = gc_message.UpdateMessageRequest() + + assert args[0] == request_msg + + +# This test is a coverage 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_message_empty_call_grpc_asyncio(): + client = ChatServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.delete_message), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_message(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = message.DeleteMessageRequest() + + assert args[0] == request_msg + + +# This test is a coverage 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_attachment_empty_call_grpc_asyncio(): + client = ChatServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_attachment), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + attachment.Attachment( + name="name_value", + content_name="content_name_value", + content_type="content_type_value", + thumbnail_uri="thumbnail_uri_value", + download_uri="download_uri_value", + source=attachment.Attachment.Source.DRIVE_FILE, + ) + ) + await client.get_attachment(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = attachment.GetAttachmentRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_upload_attachment_empty_call_grpc_asyncio(): + client = ChatServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.upload_attachment), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + attachment.UploadAttachmentResponse() + ) + await client.upload_attachment(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = attachment.UploadAttachmentRequest() + + assert args[0] == request_msg + + +# This test is a coverage 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_spaces_empty_call_grpc_asyncio(): + client = ChatServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.list_spaces), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + space.ListSpacesResponse( + next_page_token="next_page_token_value", + ) + ) + await client.list_spaces(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = space.ListSpacesRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_search_spaces_empty_call_grpc_asyncio(): + client = ChatServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.search_spaces), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + space.SearchSpacesResponse( + next_page_token="next_page_token_value", + total_size=1086, + ) + ) + await client.search_spaces(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = space.SearchSpacesRequest() + + assert args[0] == request_msg + + +# This test is a coverage 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_space_empty_call_grpc_asyncio(): + client = ChatServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_space), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + space.Space( + name="name_value", + type_=space.Space.Type.ROOM, + space_type=space.Space.SpaceType.SPACE, + single_user_bot_dm=True, + threaded=True, + display_name="display_name_value", + external_user_allowed=True, + space_threading_state=space.Space.SpaceThreadingState.THREADED_MESSAGES, + space_history_state=history_state.HistoryState.HISTORY_OFF, + import_mode=True, + admin_installed=True, + customer="customer_value", + space_uri="space_uri_value", + ) + ) + await client.get_space(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = space.GetSpaceRequest() + + assert args[0] == request_msg + + +# This test is a coverage 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_space_empty_call_grpc_asyncio(): + client = ChatServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.create_space), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gc_space.Space( + name="name_value", + type_=gc_space.Space.Type.ROOM, + space_type=gc_space.Space.SpaceType.SPACE, + single_user_bot_dm=True, + threaded=True, + display_name="display_name_value", + external_user_allowed=True, + space_threading_state=gc_space.Space.SpaceThreadingState.THREADED_MESSAGES, + space_history_state=history_state.HistoryState.HISTORY_OFF, + import_mode=True, + admin_installed=True, + customer="customer_value", + space_uri="space_uri_value", + ) + ) + await client.create_space(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = gc_space.CreateSpaceRequest() + + assert args[0] == request_msg + + +# This test is a coverage 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_space_empty_call_grpc_asyncio(): + client = ChatServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.set_up_space), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + space.Space( + name="name_value", + type_=space.Space.Type.ROOM, + space_type=space.Space.SpaceType.SPACE, + single_user_bot_dm=True, + threaded=True, + display_name="display_name_value", + external_user_allowed=True, + space_threading_state=space.Space.SpaceThreadingState.THREADED_MESSAGES, + space_history_state=history_state.HistoryState.HISTORY_OFF, + import_mode=True, + admin_installed=True, + customer="customer_value", + space_uri="space_uri_value", + ) + ) + await client.set_up_space(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = space_setup.SetUpSpaceRequest() + + assert args[0] == request_msg + + +# This test is a coverage 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_space_empty_call_grpc_asyncio(): + client = ChatServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.update_space), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gc_space.Space( + name="name_value", + type_=gc_space.Space.Type.ROOM, + space_type=gc_space.Space.SpaceType.SPACE, + single_user_bot_dm=True, + threaded=True, + display_name="display_name_value", + external_user_allowed=True, + space_threading_state=gc_space.Space.SpaceThreadingState.THREADED_MESSAGES, + space_history_state=history_state.HistoryState.HISTORY_OFF, + import_mode=True, + admin_installed=True, + customer="customer_value", + space_uri="space_uri_value", + ) + ) + await client.update_space(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = gc_space.UpdateSpaceRequest() + + assert args[0] == request_msg + + +# This test is a coverage 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_space_empty_call_grpc_asyncio(): + client = ChatServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.delete_space), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_space(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = space.DeleteSpaceRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_complete_import_space_empty_call_grpc_asyncio(): + client = ChatServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.complete_import_space), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + space.CompleteImportSpaceResponse() + ) + await client.complete_import_space(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = space.CompleteImportSpaceRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_find_direct_message_empty_call_grpc_asyncio(): + client = ChatServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.find_direct_message), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + space.Space( + name="name_value", + type_=space.Space.Type.ROOM, + space_type=space.Space.SpaceType.SPACE, + single_user_bot_dm=True, + threaded=True, + display_name="display_name_value", + external_user_allowed=True, + space_threading_state=space.Space.SpaceThreadingState.THREADED_MESSAGES, + space_history_state=history_state.HistoryState.HISTORY_OFF, + import_mode=True, + admin_installed=True, + customer="customer_value", + space_uri="space_uri_value", + ) + ) + await client.find_direct_message(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = space.FindDirectMessageRequest() + + assert args[0] == request_msg + + +# This test is a coverage 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_membership_empty_call_grpc_asyncio(): + client = ChatServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_membership), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gc_membership.Membership( + name="name_value", + state=gc_membership.Membership.MembershipState.JOINED, + role=gc_membership.Membership.MembershipRole.ROLE_MEMBER, + ) + ) + await client.create_membership(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = gc_membership.CreateMembershipRequest() + + assert args[0] == request_msg + + +# This test is a coverage 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_membership_empty_call_grpc_asyncio(): + client = ChatServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_membership), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gc_membership.Membership( + name="name_value", + state=gc_membership.Membership.MembershipState.JOINED, + role=gc_membership.Membership.MembershipRole.ROLE_MEMBER, + ) + ) + await client.update_membership(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = gc_membership.UpdateMembershipRequest() + + assert args[0] == request_msg + + +# This test is a coverage 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_membership_empty_call_grpc_asyncio(): + client = ChatServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_membership), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + membership.Membership( + name="name_value", + state=membership.Membership.MembershipState.JOINED, + role=membership.Membership.MembershipRole.ROLE_MEMBER, + ) + ) + await client.delete_membership(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = membership.DeleteMembershipRequest() + + assert args[0] == request_msg + + +# This test is a coverage 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_reaction_empty_call_grpc_asyncio(): + client = ChatServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.create_reaction), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gc_reaction.Reaction( + name="name_value", + ) + ) + await client.create_reaction(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = gc_reaction.CreateReactionRequest() + + assert args[0] == request_msg + + +# This test is a coverage 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_reactions_empty_call_grpc_asyncio(): + client = ChatServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.list_reactions), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + reaction.ListReactionsResponse( + next_page_token="next_page_token_value", + ) + ) + await client.list_reactions(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = reaction.ListReactionsRequest() + + assert args[0] == request_msg + + +# This test is a coverage 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_reaction_empty_call_grpc_asyncio(): + client = ChatServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.delete_reaction), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_reaction(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = reaction.DeleteReactionRequest() + + assert args[0] == request_msg + + +# This test is a coverage 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_custom_emoji_empty_call_grpc_asyncio(): + client = ChatServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_custom_emoji), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + reaction.CustomEmoji( + name="name_value", + uid="uid_value", + emoji_name="emoji_name_value", + temporary_image_uri="temporary_image_uri_value", + ) + ) + await client.create_custom_emoji(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = reaction.CreateCustomEmojiRequest() + + assert args[0] == request_msg + + +# This test is a coverage 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_custom_emoji_empty_call_grpc_asyncio(): + client = ChatServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_custom_emoji), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + reaction.CustomEmoji( + name="name_value", + uid="uid_value", + emoji_name="emoji_name_value", + temporary_image_uri="temporary_image_uri_value", + ) + ) + await client.get_custom_emoji(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = reaction.GetCustomEmojiRequest() + + assert args[0] == request_msg + + +# This test is a coverage 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_custom_emojis_empty_call_grpc_asyncio(): + client = ChatServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_custom_emojis), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + reaction.ListCustomEmojisResponse( + next_page_token="next_page_token_value", + ) + ) + await client.list_custom_emojis(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = reaction.ListCustomEmojisRequest() + + assert args[0] == request_msg + + +# This test is a coverage 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_custom_emoji_empty_call_grpc_asyncio(): + client = ChatServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_custom_emoji), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_custom_emoji(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = reaction.DeleteCustomEmojiRequest() + + assert args[0] == request_msg + + +# This test is a coverage 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_space_read_state_empty_call_grpc_asyncio(): + client = ChatServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_space_read_state), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + space_read_state.SpaceReadState( + name="name_value", + ) + ) + await client.get_space_read_state(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = space_read_state.GetSpaceReadStateRequest() + + assert args[0] == request_msg + + +# This test is a coverage 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_space_read_state_empty_call_grpc_asyncio(): + client = ChatServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_space_read_state), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gc_space_read_state.SpaceReadState( + name="name_value", + ) + ) + await client.update_space_read_state(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = gc_space_read_state.UpdateSpaceReadStateRequest() + + assert args[0] == request_msg + + +# This test is a coverage 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_thread_read_state_empty_call_grpc_asyncio(): + client = ChatServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_thread_read_state), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + thread_read_state.ThreadReadState( + name="name_value", + ) + ) + await client.get_thread_read_state(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = thread_read_state.GetThreadReadStateRequest() + + assert args[0] == request_msg + + +# This test is a coverage 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_space_event_empty_call_grpc_asyncio(): + client = ChatServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_space_event), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + space_event.SpaceEvent( + name="name_value", + event_type="event_type_value", + ) + ) + await client.get_space_event(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = space_event.GetSpaceEventRequest() + + assert args[0] == request_msg + + +# This test is a coverage 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_space_events_empty_call_grpc_asyncio(): + client = ChatServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_space_events), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + space_event.ListSpaceEventsResponse( + next_page_token="next_page_token_value", + ) + ) + await client.list_space_events(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = space_event.ListSpaceEventsRequest() + + assert args[0] == request_msg + + +# This test is a coverage 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_space_notification_setting_empty_call_grpc_asyncio(): + client = ChatServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_space_notification_setting), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + space_notification_setting.SpaceNotificationSetting( + name="name_value", + notification_setting=space_notification_setting.SpaceNotificationSetting.NotificationSetting.ALL, + mute_setting=space_notification_setting.SpaceNotificationSetting.MuteSetting.UNMUTED, + ) + ) + await client.get_space_notification_setting(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = space_notification_setting.GetSpaceNotificationSettingRequest() + + assert args[0] == request_msg + + +# This test is a coverage 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_space_notification_setting_empty_call_grpc_asyncio(): + client = ChatServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_space_notification_setting), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gc_space_notification_setting.SpaceNotificationSetting( + name="name_value", + notification_setting=gc_space_notification_setting.SpaceNotificationSetting.NotificationSetting.ALL, + mute_setting=gc_space_notification_setting.SpaceNotificationSetting.MuteSetting.UNMUTED, + ) + ) + await client.update_space_notification_setting(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = ( + gc_space_notification_setting.UpdateSpaceNotificationSettingRequest() + ) + + assert args[0] == request_msg + + +# This test is a coverage 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_section_empty_call_grpc_asyncio(): + client = ChatServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.create_section), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gc_section.Section( + name="name_value", + display_name="display_name_value", + sort_order=1091, + type_=gc_section.Section.SectionType.CUSTOM_SECTION, + ) + ) + await client.create_section(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = gc_section.CreateSectionRequest() + + assert args[0] == request_msg + + +# This test is a coverage 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_section_empty_call_grpc_asyncio(): + client = ChatServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.delete_section), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_section(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = section.DeleteSectionRequest() + + assert args[0] == request_msg + + +# This test is a coverage 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_section_empty_call_grpc_asyncio(): + client = ChatServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.update_section), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gc_section.Section( + name="name_value", + display_name="display_name_value", + sort_order=1091, + type_=gc_section.Section.SectionType.CUSTOM_SECTION, + ) + ) + await client.update_section(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = gc_section.UpdateSectionRequest() + + assert args[0] == request_msg + + +# This test is a coverage 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_sections_empty_call_grpc_asyncio(): + client = ChatServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.list_sections), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + section.ListSectionsResponse( + next_page_token="next_page_token_value", + ) + ) + await client.list_sections(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = section.ListSectionsRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_position_section_empty_call_grpc_asyncio(): + client = ChatServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.position_section), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + section.PositionSectionResponse() + ) + await client.position_section(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = section.PositionSectionRequest() + + assert args[0] == request_msg + + +# This test is a coverage 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_section_items_empty_call_grpc_asyncio(): + client = ChatServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_section_items), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + section.ListSectionItemsResponse( + next_page_token="next_page_token_value", + ) + ) + await client.list_section_items(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = section.ListSectionItemsRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_move_section_item_empty_call_grpc_asyncio(): + client = ChatServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.move_section_item), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + section.MoveSectionItemResponse() + ) + await client.move_section_item(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = section.MoveSectionItemRequest() + + assert args[0] == request_msg + + +def test_transport_kind_rest(): + transport = ChatServiceClient.get_transport_class("rest")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "rest" + + +def test_create_message_rest_bad_request(request_type=gc_message.CreateMessageRequest): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"parent": "spaces/sample1"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.create_message(request) + + +@pytest.mark.parametrize( + "request_type", + [ + gc_message.CreateMessageRequest, + dict, + ], +) +def test_create_message_rest_call_success(request_type): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "spaces/sample1"} + request_init["message"] = { + "name": "name_value", + "sender": { + "name": "name_value", + "display_name": "display_name_value", + "domain_id": "domain_id_value", + "type_": 1, + "is_anonymous": True, + }, + "create_time": {"seconds": 751, "nanos": 543}, + "last_update_time": {}, + "delete_time": {}, + "text": "text_value", + "formatted_text": "formatted_text_value", + "cards": [ + { + "header": { + "title": "title_value", + "subtitle": "subtitle_value", + "image_style": 1, + "image_url": "image_url_value", + }, + "sections": [ + { + "header": "header_value", + "widgets": [ + { + "text_paragraph": {"text": "text_value"}, + "image": { + "image_url": "image_url_value", + "on_click": { + "action": { + "action_method_name": "action_method_name_value", + "parameters": [ + { + "key": "key_value", + "value": "value_value", + } + ], + }, + "open_link": {"url": "url_value"}, + }, + "aspect_ratio": 0.1278, + }, + "key_value": { + "icon": 1, + "icon_url": "icon_url_value", + "top_label": "top_label_value", + "content": "content_value", + "content_multiline": True, + "bottom_label": "bottom_label_value", + "on_click": {}, + "button": { + "text_button": { + "text": "text_value", + "on_click": {}, + }, + "image_button": { + "icon": 1, + "icon_url": "icon_url_value", + "on_click": {}, + "name": "name_value", + }, + }, + }, + "buttons": {}, + } + ], + } + ], + "card_actions": [ + {"action_label": "action_label_value", "on_click": {}} + ], + "name": "name_value", + } + ], + "cards_v2": [ + { + "card_id": "card_id_value", + "card": { + "header": { + "title": "title_value", + "subtitle": "subtitle_value", + "image_type": 1, + "image_url": "image_url_value", + "image_alt_text": "image_alt_text_value", + }, + "sections": [ + { + "header": "header_value", + "widgets": [ + { + "text_paragraph": { + "text": "text_value", + "max_lines": 960, + "text_syntax": 1, + }, + "image": { + "image_url": "image_url_value", + "on_click": { + "action": { + "function": "function_value", + "parameters": [ + { + "key": "key_value", + "value": "value_value", + } + ], + "load_indicator": 1, + "persist_values": True, + "interaction": 1, + "required_widgets": [ + "required_widgets_value1", + "required_widgets_value2", + ], + "all_widgets_are_required": True, + }, + "open_link": { + "url": "url_value", + "open_as": 1, + "on_close": 1, + }, + "open_dynamic_link_action": {}, + "card": {}, + "overflow_menu": { + "items": [ + { + "start_icon": { + "known_icon": "known_icon_value", + "icon_url": "icon_url_value", + "material_icon": { + "name": "name_value", + "fill": True, + "weight": 648, "grade": 515, }, "alt_text": "alt_text_value", @@ -23832,82 +28182,860 @@ def test_update_message_rest_call_success(request_type): # 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 = gc_message.UpdateMessageRequest.meta.fields["message"] + # Determine if the message type is proto-plus or protobuf + test_field = gc_message.UpdateMessageRequest.meta.fields["message"] + + 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["message"].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["message"][field])): + del request_init["message"][field][i][subfield] + else: + del request_init["message"][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 = gc_message.Message( + name="name_value", + text="text_value", + formatted_text="formatted_text_value", + fallback_text="fallback_text_value", + argument_text="argument_text_value", + thread_reply=True, + client_assigned_message_id="client_assigned_message_id_value", + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = gc_message.Message.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_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_message(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, gc_message.Message) + assert response.name == "name_value" + assert response.text == "text_value" + assert response.formatted_text == "formatted_text_value" + assert response.fallback_text == "fallback_text_value" + assert response.argument_text == "argument_text_value" + assert response.thread_reply is True + assert response.client_assigned_message_id == "client_assigned_message_id_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_message_rest_interceptors(null_interceptor): + transport = transports.ChatServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.ChatServiceRestInterceptor(), + ) + client = ChatServiceClient(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.ChatServiceRestInterceptor, "post_update_message" + ) as post, + mock.patch.object( + transports.ChatServiceRestInterceptor, "post_update_message_with_metadata" + ) as post_with_metadata, + mock.patch.object( + transports.ChatServiceRestInterceptor, "pre_update_message" + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = gc_message.UpdateMessageRequest.pb( + gc_message.UpdateMessageRequest() + ) + 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 = gc_message.Message.to_json(gc_message.Message()) + req.return_value.content = return_value + + request = gc_message.UpdateMessageRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = gc_message.Message() + post_with_metadata.return_value = gc_message.Message(), metadata + + client.update_message( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_delete_message_rest_bad_request(request_type=message.DeleteMessageRequest): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"name": "spaces/sample1/messages/sample2"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.delete_message(request) + + +@pytest.mark.parametrize( + "request_type", + [ + message.DeleteMessageRequest, + dict, + ], +) +def test_delete_message_rest_call_success(request_type): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"name": "spaces/sample1/messages/sample2"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = None + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = "" + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.delete_message(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_message_rest_interceptors(null_interceptor): + transport = transports.ChatServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.ChatServiceRestInterceptor(), + ) + client = ChatServiceClient(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.ChatServiceRestInterceptor, "pre_delete_message" + ) as pre, + ): + pre.assert_not_called() + pb_message = message.DeleteMessageRequest.pb(message.DeleteMessageRequest()) + 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 = message.DeleteMessageRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + + client.delete_message( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + + +def test_get_attachment_rest_bad_request(request_type=attachment.GetAttachmentRequest): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"name": "spaces/sample1/messages/sample2/attachments/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_attachment(request) + + +@pytest.mark.parametrize( + "request_type", + [ + attachment.GetAttachmentRequest, + dict, + ], +) +def test_get_attachment_rest_call_success(request_type): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"name": "spaces/sample1/messages/sample2/attachments/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 = attachment.Attachment( + name="name_value", + content_name="content_name_value", + content_type="content_type_value", + thumbnail_uri="thumbnail_uri_value", + download_uri="download_uri_value", + source=attachment.Attachment.Source.DRIVE_FILE, + ) + + # 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 = attachment.Attachment.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_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_attachment(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, attachment.Attachment) + assert response.name == "name_value" + assert response.content_name == "content_name_value" + assert response.content_type == "content_type_value" + assert response.thumbnail_uri == "thumbnail_uri_value" + assert response.download_uri == "download_uri_value" + assert response.source == attachment.Attachment.Source.DRIVE_FILE + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_attachment_rest_interceptors(null_interceptor): + transport = transports.ChatServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.ChatServiceRestInterceptor(), + ) + client = ChatServiceClient(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.ChatServiceRestInterceptor, "post_get_attachment" + ) as post, + mock.patch.object( + transports.ChatServiceRestInterceptor, "post_get_attachment_with_metadata" + ) as post_with_metadata, + mock.patch.object( + transports.ChatServiceRestInterceptor, "pre_get_attachment" + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = attachment.GetAttachmentRequest.pb( + attachment.GetAttachmentRequest() + ) + 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 = attachment.Attachment.to_json(attachment.Attachment()) + req.return_value.content = return_value + + request = attachment.GetAttachmentRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = attachment.Attachment() + post_with_metadata.return_value = attachment.Attachment(), metadata + + client.get_attachment( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_upload_attachment_rest_bad_request( + request_type=attachment.UploadAttachmentRequest, +): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"parent": "spaces/sample1"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.upload_attachment(request) + + +@pytest.mark.parametrize( + "request_type", + [ + attachment.UploadAttachmentRequest, + dict, + ], +) +def test_upload_attachment_rest_call_success(request_type): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "spaces/sample1"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = attachment.UploadAttachmentResponse() + + # 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 = attachment.UploadAttachmentResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.upload_attachment(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, attachment.UploadAttachmentResponse) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_upload_attachment_rest_interceptors(null_interceptor): + transport = transports.ChatServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.ChatServiceRestInterceptor(), + ) + client = ChatServiceClient(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.ChatServiceRestInterceptor, "post_upload_attachment" + ) as post, + mock.patch.object( + transports.ChatServiceRestInterceptor, + "post_upload_attachment_with_metadata", + ) as post_with_metadata, + mock.patch.object( + transports.ChatServiceRestInterceptor, "pre_upload_attachment" + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = attachment.UploadAttachmentRequest.pb( + attachment.UploadAttachmentRequest() + ) + 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 = attachment.UploadAttachmentResponse.to_json( + attachment.UploadAttachmentResponse() + ) + req.return_value.content = return_value + + request = attachment.UploadAttachmentRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = attachment.UploadAttachmentResponse() + post_with_metadata.return_value = ( + attachment.UploadAttachmentResponse(), + metadata, + ) + + client.upload_attachment( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_list_spaces_rest_bad_request(request_type=space.ListSpacesRequest): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {} + 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_spaces(request) + + +@pytest.mark.parametrize( + "request_type", + [ + space.ListSpacesRequest, + dict, + ], +) +def test_list_spaces_rest_call_success(request_type): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = space.ListSpacesResponse( + 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 = space.ListSpacesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_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_spaces(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListSpacesPager) + assert response.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 = [] - if hasattr(field, "message") and field.message: - is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_spaces_rest_interceptors(null_interceptor): + transport = transports.ChatServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.ChatServiceRestInterceptor(), + ) + client = ChatServiceClient(transport=transport) - 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 + with ( + mock.patch.object(type(client.transport._session), "request") as req, + mock.patch.object(path_template, "transcode") as transcode, + mock.patch.object( + transports.ChatServiceRestInterceptor, "post_list_spaces" + ) as post, + mock.patch.object( + transports.ChatServiceRestInterceptor, "post_list_spaces_with_metadata" + ) as post_with_metadata, + mock.patch.object( + transports.ChatServiceRestInterceptor, "pre_list_spaces" + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = space.ListSpacesRequest.pb(space.ListSpacesRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } - runtime_nested_fields = [ - (field.name, nested_field.name) - for field in get_message_fields(test_field) - for nested_field in get_message_fields(field) - ] + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = space.ListSpacesResponse.to_json(space.ListSpacesResponse()) + req.return_value.content = return_value - subfields_not_in_runtime = [] + request = space.ListSpacesRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = space.ListSpacesResponse() + post_with_metadata.return_value = space.ListSpacesResponse(), metadata - # 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["message"].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 + client.list_spaces( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) - 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, - } - ) + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_search_spaces_rest_bad_request(request_type=space.SearchSpacesRequest): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {} + 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_spaces(request) + + +@pytest.mark.parametrize( + "request_type", + [ + space.SearchSpacesRequest, + dict, + ], +) +def test_search_spaces_rest_call_success(request_type): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = space.SearchSpacesResponse( + next_page_token="next_page_token_value", + total_size=1086, + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = space.SearchSpacesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_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_spaces(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.SearchSpacesPager) + assert response.next_page_token == "next_page_token_value" + assert response.total_size == 1086 + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_search_spaces_rest_interceptors(null_interceptor): + transport = transports.ChatServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.ChatServiceRestInterceptor(), + ) + client = ChatServiceClient(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.ChatServiceRestInterceptor, "post_search_spaces" + ) as post, + mock.patch.object( + transports.ChatServiceRestInterceptor, "post_search_spaces_with_metadata" + ) as post_with_metadata, + mock.patch.object( + transports.ChatServiceRestInterceptor, "pre_search_spaces" + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = space.SearchSpacesRequest.pb(space.SearchSpacesRequest()) + 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 = space.SearchSpacesResponse.to_json(space.SearchSpacesResponse()) + req.return_value.content = return_value + + request = space.SearchSpacesRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = space.SearchSpacesResponse() + post_with_metadata.return_value = space.SearchSpacesResponse(), metadata + + client.search_spaces( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_get_space_rest_bad_request(request_type=space.GetSpaceRequest): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"name": "spaces/sample1"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.get_space(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["message"][field])): - del request_init["message"][field][i][subfield] - else: - del request_init["message"][field][subfield] + +@pytest.mark.parametrize( + "request_type", + [ + space.GetSpaceRequest, + dict, + ], +) +def test_get_space_rest_call_success(request_type): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"name": "spaces/sample1"} request = request_type(**request_init) # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = gc_message.Message( + return_value = space.Space( name="name_value", - text="text_value", - formatted_text="formatted_text_value", - fallback_text="fallback_text_value", - argument_text="argument_text_value", - thread_reply=True, - client_assigned_message_id="client_assigned_message_id_value", + type_=space.Space.Type.ROOM, + space_type=space.Space.SpaceType.SPACE, + single_user_bot_dm=True, + threaded=True, + display_name="display_name_value", + external_user_allowed=True, + space_threading_state=space.Space.SpaceThreadingState.THREADED_MESSAGES, + space_history_state=history_state.HistoryState.HISTORY_OFF, + import_mode=True, + admin_installed=True, + customer="customer_value", + space_uri="space_uri_value", + predefined_permission_settings=space.Space.PredefinedPermissionSettings.COLLABORATION_SPACE, ) # Wrap the value into a proper Response obj @@ -23915,26 +29043,35 @@ def get_message_fields(field): response_value.status_code = 200 # Convert return value to protobuf type - return_value = gc_message.Message.pb(return_value) + return_value = space.Space.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value.content = json_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_message(request) + response = client.get_space(request) # Establish that the response is the type that we expect. - assert isinstance(response, gc_message.Message) + assert isinstance(response, space.Space) assert response.name == "name_value" - assert response.text == "text_value" - assert response.formatted_text == "formatted_text_value" - assert response.fallback_text == "fallback_text_value" - assert response.argument_text == "argument_text_value" - assert response.thread_reply is True - assert response.client_assigned_message_id == "client_assigned_message_id_value" + assert response.type_ == space.Space.Type.ROOM + assert response.space_type == space.Space.SpaceType.SPACE + assert response.single_user_bot_dm is True + assert response.threaded is True + assert response.display_name == "display_name_value" + assert response.external_user_allowed is True + assert ( + response.space_threading_state + == space.Space.SpaceThreadingState.THREADED_MESSAGES + ) + assert response.space_history_state == history_state.HistoryState.HISTORY_OFF + assert response.import_mode is True + assert response.admin_installed is True + assert response.customer == "customer_value" + assert response.space_uri == "space_uri_value" @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_update_message_rest_interceptors(null_interceptor): +def test_get_space_rest_interceptors(null_interceptor): transport = transports.ChatServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -23947,21 +29084,19 @@ def test_update_message_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.ChatServiceRestInterceptor, "post_update_message" + transports.ChatServiceRestInterceptor, "post_get_space" ) as post, mock.patch.object( - transports.ChatServiceRestInterceptor, "post_update_message_with_metadata" + transports.ChatServiceRestInterceptor, "post_get_space_with_metadata" ) as post_with_metadata, mock.patch.object( - transports.ChatServiceRestInterceptor, "pre_update_message" + transports.ChatServiceRestInterceptor, "pre_get_space" ) as pre, ): pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = gc_message.UpdateMessageRequest.pb( - gc_message.UpdateMessageRequest() - ) + pb_message = space.GetSpaceRequest.pb(space.GetSpaceRequest()) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -23972,19 +29107,19 @@ def test_update_message_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 = gc_message.Message.to_json(gc_message.Message()) + return_value = space.Space.to_json(space.Space()) req.return_value.content = return_value - request = gc_message.UpdateMessageRequest() + request = space.GetSpaceRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = gc_message.Message() - post_with_metadata.return_value = gc_message.Message(), metadata + post.return_value = space.Space() + post_with_metadata.return_value = space.Space(), metadata - client.update_message( + client.get_space( request, metadata=[ ("key", "val"), @@ -23997,12 +29132,12 @@ def test_update_message_rest_interceptors(null_interceptor): post_with_metadata.assert_called_once() -def test_delete_message_rest_bad_request(request_type=message.DeleteMessageRequest): +def test_create_space_rest_bad_request(request_type=gc_space.CreateSpaceRequest): client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {"name": "spaces/sample1/messages/sample2"} + request_init = {} request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -24018,45 +29153,188 @@ def test_delete_message_rest_bad_request(request_type=message.DeleteMessageReque response_value.request = mock.Mock() req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.delete_message(request) + client.create_space(request) @pytest.mark.parametrize( "request_type", [ - message.DeleteMessageRequest, + gc_space.CreateSpaceRequest, dict, ], ) -def test_delete_message_rest_call_success(request_type): +def test_create_space_rest_call_success(request_type): client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {"name": "spaces/sample1/messages/sample2"} + request_init = {} + request_init["space"] = { + "name": "name_value", + "type_": 1, + "space_type": 1, + "single_user_bot_dm": True, + "threaded": True, + "display_name": "display_name_value", + "external_user_allowed": True, + "space_threading_state": 2, + "space_details": { + "description": "description_value", + "guidelines": "guidelines_value", + }, + "space_history_state": 1, + "import_mode": True, + "create_time": {"seconds": 751, "nanos": 543}, + "last_active_time": {}, + "admin_installed": True, + "membership_count": { + "joined_direct_human_user_count": 3185, + "joined_group_count": 1933, + }, + "access_settings": {"access_state": 1, "audience": "audience_value"}, + "customer": "customer_value", + "space_uri": "space_uri_value", + "predefined_permission_settings": 1, + "permission_settings": { + "manage_members_and_groups": { + "managers_allowed": True, + "assistant_managers_allowed": True, + "members_allowed": True, + }, + "modify_space_details": {}, + "toggle_history": {}, + "use_at_mention_all": {}, + "manage_apps": {}, + "manage_webhooks": {}, + "post_messages": {}, + "reply_messages": {}, + }, + "import_mode_expire_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 = gc_space.CreateSpaceRequest.meta.fields["space"] + + 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["space"].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["space"][field])): + del request_init["space"][field][i][subfield] + else: + del request_init["space"][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 = None + return_value = gc_space.Space( + name="name_value", + type_=gc_space.Space.Type.ROOM, + space_type=gc_space.Space.SpaceType.SPACE, + single_user_bot_dm=True, + threaded=True, + display_name="display_name_value", + external_user_allowed=True, + space_threading_state=gc_space.Space.SpaceThreadingState.THREADED_MESSAGES, + space_history_state=history_state.HistoryState.HISTORY_OFF, + import_mode=True, + admin_installed=True, + customer="customer_value", + space_uri="space_uri_value", + predefined_permission_settings=gc_space.Space.PredefinedPermissionSettings.COLLABORATION_SPACE, + ) # Wrap the value into a proper Response obj response_value = mock.Mock() response_value.status_code = 200 - json_return_value = "" + + # Convert return value to protobuf type + return_value = gc_space.Space.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) response_value.content = json_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_message(request) + response = client.create_space(request) # Establish that the response is the type that we expect. - assert response is None + assert isinstance(response, gc_space.Space) + assert response.name == "name_value" + assert response.type_ == gc_space.Space.Type.ROOM + assert response.space_type == gc_space.Space.SpaceType.SPACE + assert response.single_user_bot_dm is True + assert response.threaded is True + assert response.display_name == "display_name_value" + assert response.external_user_allowed is True + assert ( + response.space_threading_state + == gc_space.Space.SpaceThreadingState.THREADED_MESSAGES + ) + assert response.space_history_state == history_state.HistoryState.HISTORY_OFF + assert response.import_mode is True + assert response.admin_installed is True + assert response.customer == "customer_value" + assert response.space_uri == "space_uri_value" @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_delete_message_rest_interceptors(null_interceptor): +def test_create_space_rest_interceptors(null_interceptor): transport = transports.ChatServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -24069,11 +29347,19 @@ def test_delete_message_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.ChatServiceRestInterceptor, "pre_delete_message" + transports.ChatServiceRestInterceptor, "post_create_space" + ) as post, + mock.patch.object( + transports.ChatServiceRestInterceptor, "post_create_space_with_metadata" + ) as post_with_metadata, + mock.patch.object( + transports.ChatServiceRestInterceptor, "pre_create_space" ) as pre, ): pre.assert_not_called() - pb_message = message.DeleteMessageRequest.pb(message.DeleteMessageRequest()) + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = gc_space.CreateSpaceRequest.pb(gc_space.CreateSpaceRequest()) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -24084,15 +29370,19 @@ def test_delete_message_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 = gc_space.Space.to_json(gc_space.Space()) + req.return_value.content = return_value - request = message.DeleteMessageRequest() + request = gc_space.CreateSpaceRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata + post.return_value = gc_space.Space() + post_with_metadata.return_value = gc_space.Space(), metadata - client.delete_message( + client.create_space( request, metadata=[ ("key", "val"), @@ -24101,14 +29391,16 @@ def test_delete_message_rest_interceptors(null_interceptor): ) pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() -def test_get_attachment_rest_bad_request(request_type=attachment.GetAttachmentRequest): +def test_set_up_space_rest_bad_request(request_type=space_setup.SetUpSpaceRequest): client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {"name": "spaces/sample1/messages/sample2/attachments/sample3"} + request_init = {} request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -24124,35 +29416,43 @@ def test_get_attachment_rest_bad_request(request_type=attachment.GetAttachmentRe response_value.request = mock.Mock() req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.get_attachment(request) + client.set_up_space(request) @pytest.mark.parametrize( "request_type", [ - attachment.GetAttachmentRequest, + space_setup.SetUpSpaceRequest, dict, ], ) -def test_get_attachment_rest_call_success(request_type): +def test_set_up_space_rest_call_success(request_type): client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {"name": "spaces/sample1/messages/sample2/attachments/sample3"} + request_init = {} request = request_type(**request_init) # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = attachment.Attachment( + return_value = space.Space( name="name_value", - content_name="content_name_value", - content_type="content_type_value", - thumbnail_uri="thumbnail_uri_value", - download_uri="download_uri_value", - source=attachment.Attachment.Source.DRIVE_FILE, + type_=space.Space.Type.ROOM, + space_type=space.Space.SpaceType.SPACE, + single_user_bot_dm=True, + threaded=True, + display_name="display_name_value", + external_user_allowed=True, + space_threading_state=space.Space.SpaceThreadingState.THREADED_MESSAGES, + space_history_state=history_state.HistoryState.HISTORY_OFF, + import_mode=True, + admin_installed=True, + customer="customer_value", + space_uri="space_uri_value", + predefined_permission_settings=space.Space.PredefinedPermissionSettings.COLLABORATION_SPACE, ) # Wrap the value into a proper Response obj @@ -24160,25 +29460,35 @@ def test_get_attachment_rest_call_success(request_type): response_value.status_code = 200 # Convert return value to protobuf type - return_value = attachment.Attachment.pb(return_value) + return_value = space.Space.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value.content = json_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_attachment(request) + response = client.set_up_space(request) # Establish that the response is the type that we expect. - assert isinstance(response, attachment.Attachment) + assert isinstance(response, space.Space) assert response.name == "name_value" - assert response.content_name == "content_name_value" - assert response.content_type == "content_type_value" - assert response.thumbnail_uri == "thumbnail_uri_value" - assert response.download_uri == "download_uri_value" - assert response.source == attachment.Attachment.Source.DRIVE_FILE + assert response.type_ == space.Space.Type.ROOM + assert response.space_type == space.Space.SpaceType.SPACE + assert response.single_user_bot_dm is True + assert response.threaded is True + assert response.display_name == "display_name_value" + assert response.external_user_allowed is True + assert ( + response.space_threading_state + == space.Space.SpaceThreadingState.THREADED_MESSAGES + ) + assert response.space_history_state == history_state.HistoryState.HISTORY_OFF + assert response.import_mode is True + assert response.admin_installed is True + assert response.customer == "customer_value" + assert response.space_uri == "space_uri_value" @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_attachment_rest_interceptors(null_interceptor): +def test_set_up_space_rest_interceptors(null_interceptor): transport = transports.ChatServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -24191,21 +29501,19 @@ def test_get_attachment_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.ChatServiceRestInterceptor, "post_get_attachment" + transports.ChatServiceRestInterceptor, "post_set_up_space" ) as post, mock.patch.object( - transports.ChatServiceRestInterceptor, "post_get_attachment_with_metadata" + transports.ChatServiceRestInterceptor, "post_set_up_space_with_metadata" ) as post_with_metadata, mock.patch.object( - transports.ChatServiceRestInterceptor, "pre_get_attachment" + transports.ChatServiceRestInterceptor, "pre_set_up_space" ) as pre, ): pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = attachment.GetAttachmentRequest.pb( - attachment.GetAttachmentRequest() - ) + pb_message = space_setup.SetUpSpaceRequest.pb(space_setup.SetUpSpaceRequest()) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -24216,19 +29524,19 @@ def test_get_attachment_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 = attachment.Attachment.to_json(attachment.Attachment()) + return_value = space.Space.to_json(space.Space()) req.return_value.content = return_value - request = attachment.GetAttachmentRequest() + request = space_setup.SetUpSpaceRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = attachment.Attachment() - post_with_metadata.return_value = attachment.Attachment(), metadata + post.return_value = space.Space() + post_with_metadata.return_value = space.Space(), metadata - client.get_attachment( + client.set_up_space( request, metadata=[ ("key", "val"), @@ -24241,14 +29549,12 @@ def test_get_attachment_rest_interceptors(null_interceptor): post_with_metadata.assert_called_once() -def test_upload_attachment_rest_bad_request( - request_type=attachment.UploadAttachmentRequest, -): +def test_update_space_rest_bad_request(request_type=gc_space.UpdateSpaceRequest): client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {"parent": "spaces/sample1"} + request_init = {"space": {"name": "spaces/sample1"}} request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -24264,161 +29570,152 @@ def test_upload_attachment_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.upload_attachment(request) + client.update_space(request) @pytest.mark.parametrize( "request_type", [ - attachment.UploadAttachmentRequest, + gc_space.UpdateSpaceRequest, dict, ], ) -def test_upload_attachment_rest_call_success(request_type): +def test_update_space_rest_call_success(request_type): client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {"parent": "spaces/sample1"} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), "request") as req: - # Designate an appropriate value for the returned response. - return_value = attachment.UploadAttachmentResponse() - - # 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 = attachment.UploadAttachmentResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode("UTF-8") - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.upload_attachment(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, attachment.UploadAttachmentResponse) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_upload_attachment_rest_interceptors(null_interceptor): - transport = transports.ChatServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.ChatServiceRestInterceptor(), - ) - client = ChatServiceClient(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.ChatServiceRestInterceptor, "post_upload_attachment" - ) as post, - mock.patch.object( - transports.ChatServiceRestInterceptor, - "post_upload_attachment_with_metadata", - ) as post_with_metadata, - mock.patch.object( - transports.ChatServiceRestInterceptor, "pre_upload_attachment" - ) as pre, - ): - pre.assert_not_called() - post.assert_not_called() - post_with_metadata.assert_not_called() - pb_message = attachment.UploadAttachmentRequest.pb( - attachment.UploadAttachmentRequest() - ) - 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 = attachment.UploadAttachmentResponse.to_json( - attachment.UploadAttachmentResponse() - ) - req.return_value.content = return_value + request_init = {"space": {"name": "spaces/sample1"}} + request_init["space"] = { + "name": "spaces/sample1", + "type_": 1, + "space_type": 1, + "single_user_bot_dm": True, + "threaded": True, + "display_name": "display_name_value", + "external_user_allowed": True, + "space_threading_state": 2, + "space_details": { + "description": "description_value", + "guidelines": "guidelines_value", + }, + "space_history_state": 1, + "import_mode": True, + "create_time": {"seconds": 751, "nanos": 543}, + "last_active_time": {}, + "admin_installed": True, + "membership_count": { + "joined_direct_human_user_count": 3185, + "joined_group_count": 1933, + }, + "access_settings": {"access_state": 1, "audience": "audience_value"}, + "customer": "customer_value", + "space_uri": "space_uri_value", + "predefined_permission_settings": 1, + "permission_settings": { + "manage_members_and_groups": { + "managers_allowed": True, + "assistant_managers_allowed": True, + "members_allowed": True, + }, + "modify_space_details": {}, + "toggle_history": {}, + "use_at_mention_all": {}, + "manage_apps": {}, + "manage_webhooks": {}, + "post_messages": {}, + "reply_messages": {}, + }, + "import_mode_expire_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 - request = attachment.UploadAttachmentRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = attachment.UploadAttachmentResponse() - post_with_metadata.return_value = ( - attachment.UploadAttachmentResponse(), - metadata, - ) + # Determine if the message type is proto-plus or protobuf + test_field = gc_space.UpdateSpaceRequest.meta.fields["space"] - client.upload_attachment( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) + 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 = [] - pre.assert_called_once() - post.assert_called_once() - post_with_metadata.assert_called_once() + 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 -def test_list_spaces_rest_bad_request(request_type=space.ListSpacesRequest): - client = ChatServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {} - request = request_type(**request_init) + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] - # Mock the http request call within the method and fake a BadRequest error. - with ( - mock.patch.object(Session, "request") as req, - pytest.raises(core_exceptions.BadRequest), - ): - # Wrap the value into a proper Response obj - response_value = mock.Mock() - json_return_value = "" - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = mock.Mock() - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.list_spaces(request) + subfields_not_in_runtime = [] + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["space"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value -@pytest.mark.parametrize( - "request_type", - [ - space.ListSpacesRequest, - dict, - ], -) -def test_list_spaces_rest_call_success(request_type): - client = ChatServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + { + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + } + ) - # send a request that will satisfy transcoding - request_init = {} + # 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["space"][field])): + del request_init["space"][field][i][subfield] + else: + del request_init["space"][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 = space.ListSpacesResponse( - next_page_token="next_page_token_value", + return_value = gc_space.Space( + name="name_value", + type_=gc_space.Space.Type.ROOM, + space_type=gc_space.Space.SpaceType.SPACE, + single_user_bot_dm=True, + threaded=True, + display_name="display_name_value", + external_user_allowed=True, + space_threading_state=gc_space.Space.SpaceThreadingState.THREADED_MESSAGES, + space_history_state=history_state.HistoryState.HISTORY_OFF, + import_mode=True, + admin_installed=True, + customer="customer_value", + space_uri="space_uri_value", + predefined_permission_settings=gc_space.Space.PredefinedPermissionSettings.COLLABORATION_SPACE, ) # Wrap the value into a proper Response obj @@ -24426,20 +29723,35 @@ def test_list_spaces_rest_call_success(request_type): response_value.status_code = 200 # Convert return value to protobuf type - return_value = space.ListSpacesResponse.pb(return_value) + return_value = gc_space.Space.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value.content = json_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_spaces(request) + response = client.update_space(request) # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListSpacesPager) - assert response.next_page_token == "next_page_token_value" + assert isinstance(response, gc_space.Space) + assert response.name == "name_value" + assert response.type_ == gc_space.Space.Type.ROOM + assert response.space_type == gc_space.Space.SpaceType.SPACE + assert response.single_user_bot_dm is True + assert response.threaded is True + assert response.display_name == "display_name_value" + assert response.external_user_allowed is True + assert ( + response.space_threading_state + == gc_space.Space.SpaceThreadingState.THREADED_MESSAGES + ) + assert response.space_history_state == history_state.HistoryState.HISTORY_OFF + assert response.import_mode is True + assert response.admin_installed is True + assert response.customer == "customer_value" + assert response.space_uri == "space_uri_value" @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_spaces_rest_interceptors(null_interceptor): +def test_update_space_rest_interceptors(null_interceptor): transport = transports.ChatServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -24452,19 +29764,19 @@ def test_list_spaces_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.ChatServiceRestInterceptor, "post_list_spaces" + transports.ChatServiceRestInterceptor, "post_update_space" ) as post, mock.patch.object( - transports.ChatServiceRestInterceptor, "post_list_spaces_with_metadata" + transports.ChatServiceRestInterceptor, "post_update_space_with_metadata" ) as post_with_metadata, mock.patch.object( - transports.ChatServiceRestInterceptor, "pre_list_spaces" + transports.ChatServiceRestInterceptor, "pre_update_space" ) as pre, ): pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = space.ListSpacesRequest.pb(space.ListSpacesRequest()) + pb_message = gc_space.UpdateSpaceRequest.pb(gc_space.UpdateSpaceRequest()) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -24475,19 +29787,19 @@ def test_list_spaces_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 = space.ListSpacesResponse.to_json(space.ListSpacesResponse()) + return_value = gc_space.Space.to_json(gc_space.Space()) req.return_value.content = return_value - request = space.ListSpacesRequest() + request = gc_space.UpdateSpaceRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = space.ListSpacesResponse() - post_with_metadata.return_value = space.ListSpacesResponse(), metadata + post.return_value = gc_space.Space() + post_with_metadata.return_value = gc_space.Space(), metadata - client.list_spaces( + client.update_space( request, metadata=[ ("key", "val"), @@ -24500,12 +29812,12 @@ def test_list_spaces_rest_interceptors(null_interceptor): post_with_metadata.assert_called_once() -def test_search_spaces_rest_bad_request(request_type=space.SearchSpacesRequest): +def test_delete_space_rest_bad_request(request_type=space.DeleteSpaceRequest): client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {} + request_init = {"name": "spaces/sample1"} request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -24521,53 +29833,45 @@ def test_search_spaces_rest_bad_request(request_type=space.SearchSpacesRequest): response_value.request = mock.Mock() req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.search_spaces(request) + client.delete_space(request) @pytest.mark.parametrize( "request_type", [ - space.SearchSpacesRequest, + space.DeleteSpaceRequest, dict, ], ) -def test_search_spaces_rest_call_success(request_type): +def test_delete_space_rest_call_success(request_type): client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {} + request_init = {"name": "spaces/sample1"} request = request_type(**request_init) # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = space.SearchSpacesResponse( - next_page_token="next_page_token_value", - total_size=1086, - ) + return_value = None # Wrap the value into a proper Response obj response_value = mock.Mock() response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = space.SearchSpacesResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) + json_return_value = "" response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.search_spaces(request) + response = client.delete_space(request) # Establish that the response is the type that we expect. - assert isinstance(response, pagers.SearchSpacesPager) - assert response.next_page_token == "next_page_token_value" - assert response.total_size == 1086 + assert response is None @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_search_spaces_rest_interceptors(null_interceptor): +def test_delete_space_rest_interceptors(null_interceptor): transport = transports.ChatServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -24580,19 +29884,11 @@ def test_search_spaces_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.ChatServiceRestInterceptor, "post_search_spaces" - ) as post, - mock.patch.object( - transports.ChatServiceRestInterceptor, "post_search_spaces_with_metadata" - ) as post_with_metadata, - mock.patch.object( - transports.ChatServiceRestInterceptor, "pre_search_spaces" + transports.ChatServiceRestInterceptor, "pre_delete_space" ) as pre, ): pre.assert_not_called() - post.assert_not_called() - post_with_metadata.assert_not_called() - pb_message = space.SearchSpacesRequest.pb(space.SearchSpacesRequest()) + pb_message = space.DeleteSpaceRequest.pb(space.DeleteSpaceRequest()) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -24603,19 +29899,15 @@ def test_search_spaces_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 = space.SearchSpacesResponse.to_json(space.SearchSpacesResponse()) - req.return_value.content = return_value - request = space.SearchSpacesRequest() + request = space.DeleteSpaceRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = space.SearchSpacesResponse() - post_with_metadata.return_value = space.SearchSpacesResponse(), metadata - client.search_spaces( + client.delete_space( request, metadata=[ ("key", "val"), @@ -24624,11 +29916,11 @@ def test_search_spaces_rest_interceptors(null_interceptor): ) pre.assert_called_once() - post.assert_called_once() - post_with_metadata.assert_called_once() -def test_get_space_rest_bad_request(request_type=space.GetSpaceRequest): +def test_complete_import_space_rest_bad_request( + request_type=space.CompleteImportSpaceRequest, +): client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) @@ -24649,17 +29941,17 @@ def test_get_space_rest_bad_request(request_type=space.GetSpaceRequest): response_value.request = mock.Mock() req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.get_space(request) + client.complete_import_space(request) @pytest.mark.parametrize( "request_type", [ - space.GetSpaceRequest, + space.CompleteImportSpaceRequest, dict, ], ) -def test_get_space_rest_call_success(request_type): +def test_complete_import_space_rest_call_success(request_type): client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) @@ -24671,57 +29963,26 @@ def test_get_space_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 = space.Space( - name="name_value", - type_=space.Space.Type.ROOM, - space_type=space.Space.SpaceType.SPACE, - single_user_bot_dm=True, - threaded=True, - display_name="display_name_value", - external_user_allowed=True, - space_threading_state=space.Space.SpaceThreadingState.THREADED_MESSAGES, - space_history_state=history_state.HistoryState.HISTORY_OFF, - import_mode=True, - admin_installed=True, - customer="customer_value", - space_uri="space_uri_value", - predefined_permission_settings=space.Space.PredefinedPermissionSettings.COLLABORATION_SPACE, - ) + return_value = space.CompleteImportSpaceResponse() # 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 = space.Space.pb(return_value) + return_value = space.CompleteImportSpaceResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value.content = json_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_space(request) + response = client.complete_import_space(request) # Establish that the response is the type that we expect. - assert isinstance(response, space.Space) - assert response.name == "name_value" - assert response.type_ == space.Space.Type.ROOM - assert response.space_type == space.Space.SpaceType.SPACE - assert response.single_user_bot_dm is True - assert response.threaded is True - assert response.display_name == "display_name_value" - assert response.external_user_allowed is True - assert ( - response.space_threading_state - == space.Space.SpaceThreadingState.THREADED_MESSAGES - ) - assert response.space_history_state == history_state.HistoryState.HISTORY_OFF - assert response.import_mode is True - assert response.admin_installed is True - assert response.customer == "customer_value" - assert response.space_uri == "space_uri_value" + assert isinstance(response, space.CompleteImportSpaceResponse) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_space_rest_interceptors(null_interceptor): +def test_complete_import_space_rest_interceptors(null_interceptor): transport = transports.ChatServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -24734,19 +29995,22 @@ def test_get_space_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.ChatServiceRestInterceptor, "post_get_space" + transports.ChatServiceRestInterceptor, "post_complete_import_space" ) as post, mock.patch.object( - transports.ChatServiceRestInterceptor, "post_get_space_with_metadata" + transports.ChatServiceRestInterceptor, + "post_complete_import_space_with_metadata", ) as post_with_metadata, mock.patch.object( - transports.ChatServiceRestInterceptor, "pre_get_space" + transports.ChatServiceRestInterceptor, "pre_complete_import_space" ) as pre, ): pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = space.GetSpaceRequest.pb(space.GetSpaceRequest()) + pb_message = space.CompleteImportSpaceRequest.pb( + space.CompleteImportSpaceRequest() + ) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -24757,19 +30021,21 @@ def test_get_space_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 = space.Space.to_json(space.Space()) + return_value = space.CompleteImportSpaceResponse.to_json( + space.CompleteImportSpaceResponse() + ) req.return_value.content = return_value - request = space.GetSpaceRequest() + request = space.CompleteImportSpaceRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = space.Space() - post_with_metadata.return_value = space.Space(), metadata + post.return_value = space.CompleteImportSpaceResponse() + post_with_metadata.return_value = space.CompleteImportSpaceResponse(), metadata - client.get_space( + client.complete_import_space( request, metadata=[ ("key", "val"), @@ -24782,7 +30048,9 @@ def test_get_space_rest_interceptors(null_interceptor): post_with_metadata.assert_called_once() -def test_create_space_rest_bad_request(request_type=gc_space.CreateSpaceRequest): +def test_find_direct_message_rest_bad_request( + request_type=space.FindDirectMessageRequest, +): client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) @@ -24803,152 +30071,43 @@ def test_create_space_rest_bad_request(request_type=gc_space.CreateSpaceRequest) response_value.request = mock.Mock() req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.create_space(request) + client.find_direct_message(request) @pytest.mark.parametrize( "request_type", [ - gc_space.CreateSpaceRequest, + space.FindDirectMessageRequest, dict, ], ) -def test_create_space_rest_call_success(request_type): +def test_find_direct_message_rest_call_success(request_type): client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding request_init = {} - request_init["space"] = { - "name": "name_value", - "type_": 1, - "space_type": 1, - "single_user_bot_dm": True, - "threaded": True, - "display_name": "display_name_value", - "external_user_allowed": True, - "space_threading_state": 2, - "space_details": { - "description": "description_value", - "guidelines": "guidelines_value", - }, - "space_history_state": 1, - "import_mode": True, - "create_time": {"seconds": 751, "nanos": 543}, - "last_active_time": {}, - "admin_installed": True, - "membership_count": { - "joined_direct_human_user_count": 3185, - "joined_group_count": 1933, - }, - "access_settings": {"access_state": 1, "audience": "audience_value"}, - "customer": "customer_value", - "space_uri": "space_uri_value", - "predefined_permission_settings": 1, - "permission_settings": { - "manage_members_and_groups": { - "managers_allowed": True, - "assistant_managers_allowed": True, - "members_allowed": True, - }, - "modify_space_details": {}, - "toggle_history": {}, - "use_at_mention_all": {}, - "manage_apps": {}, - "manage_webhooks": {}, - "post_messages": {}, - "reply_messages": {}, - }, - "import_mode_expire_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 = gc_space.CreateSpaceRequest.meta.fields["space"] - - 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["space"].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["space"][field])): - del request_init["space"][field][i][subfield] - else: - del request_init["space"][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 = gc_space.Space( + return_value = space.Space( name="name_value", - type_=gc_space.Space.Type.ROOM, - space_type=gc_space.Space.SpaceType.SPACE, + type_=space.Space.Type.ROOM, + space_type=space.Space.SpaceType.SPACE, single_user_bot_dm=True, threaded=True, display_name="display_name_value", external_user_allowed=True, - space_threading_state=gc_space.Space.SpaceThreadingState.THREADED_MESSAGES, + space_threading_state=space.Space.SpaceThreadingState.THREADED_MESSAGES, space_history_state=history_state.HistoryState.HISTORY_OFF, import_mode=True, admin_installed=True, customer="customer_value", space_uri="space_uri_value", - predefined_permission_settings=gc_space.Space.PredefinedPermissionSettings.COLLABORATION_SPACE, + predefined_permission_settings=space.Space.PredefinedPermissionSettings.COLLABORATION_SPACE, ) # Wrap the value into a proper Response obj @@ -24956,25 +30115,25 @@ def get_message_fields(field): response_value.status_code = 200 # Convert return value to protobuf type - return_value = gc_space.Space.pb(return_value) + return_value = space.Space.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value.content = json_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_space(request) + response = client.find_direct_message(request) # Establish that the response is the type that we expect. - assert isinstance(response, gc_space.Space) + assert isinstance(response, space.Space) assert response.name == "name_value" - assert response.type_ == gc_space.Space.Type.ROOM - assert response.space_type == gc_space.Space.SpaceType.SPACE + assert response.type_ == space.Space.Type.ROOM + assert response.space_type == space.Space.SpaceType.SPACE assert response.single_user_bot_dm is True assert response.threaded is True assert response.display_name == "display_name_value" assert response.external_user_allowed is True assert ( response.space_threading_state - == gc_space.Space.SpaceThreadingState.THREADED_MESSAGES + == space.Space.SpaceThreadingState.THREADED_MESSAGES ) assert response.space_history_state == history_state.HistoryState.HISTORY_OFF assert response.import_mode is True @@ -24984,7 +30143,7 @@ def get_message_fields(field): @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_create_space_rest_interceptors(null_interceptor): +def test_find_direct_message_rest_interceptors(null_interceptor): transport = transports.ChatServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -24997,19 +30156,20 @@ def test_create_space_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.ChatServiceRestInterceptor, "post_create_space" + transports.ChatServiceRestInterceptor, "post_find_direct_message" ) as post, mock.patch.object( - transports.ChatServiceRestInterceptor, "post_create_space_with_metadata" + transports.ChatServiceRestInterceptor, + "post_find_direct_message_with_metadata", ) as post_with_metadata, mock.patch.object( - transports.ChatServiceRestInterceptor, "pre_create_space" + transports.ChatServiceRestInterceptor, "pre_find_direct_message" ) as pre, ): pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = gc_space.CreateSpaceRequest.pb(gc_space.CreateSpaceRequest()) + pb_message = space.FindDirectMessageRequest.pb(space.FindDirectMessageRequest()) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -25020,19 +30180,19 @@ def test_create_space_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 = gc_space.Space.to_json(gc_space.Space()) + return_value = space.Space.to_json(space.Space()) req.return_value.content = return_value - request = gc_space.CreateSpaceRequest() + request = space.FindDirectMessageRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = gc_space.Space() - post_with_metadata.return_value = gc_space.Space(), metadata + post.return_value = space.Space() + post_with_metadata.return_value = space.Space(), metadata - client.create_space( + client.find_direct_message( request, metadata=[ ("key", "val"), @@ -25045,12 +30205,14 @@ def test_create_space_rest_interceptors(null_interceptor): post_with_metadata.assert_called_once() -def test_set_up_space_rest_bad_request(request_type=space_setup.SetUpSpaceRequest): +def test_create_membership_rest_bad_request( + request_type=gc_membership.CreateMembershipRequest, +): client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {} + request_init = {"parent": "spaces/sample1"} request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -25066,43 +30228,114 @@ def test_set_up_space_rest_bad_request(request_type=space_setup.SetUpSpaceReques 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_space(request) + client.create_membership(request) + + +@pytest.mark.parametrize( + "request_type", + [ + gc_membership.CreateMembershipRequest, + dict, + ], +) +def test_create_membership_rest_call_success(request_type): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "spaces/sample1"} + request_init["membership"] = { + "name": "name_value", + "state": 1, + "role": 1, + "member": { + "name": "name_value", + "display_name": "display_name_value", + "domain_id": "domain_id_value", + "type_": 1, + "is_anonymous": True, + }, + "group_member": {"name": "name_value"}, + "create_time": {"seconds": 751, "nanos": 543}, + "delete_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 = gc_membership.CreateMembershipRequest.meta.fields["membership"] + + 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["membership"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value -@pytest.mark.parametrize( - "request_type", - [ - space_setup.SetUpSpaceRequest, - dict, - ], -) -def test_set_up_space_rest_call_success(request_type): - client = ChatServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + { + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + } + ) - # send a request that will satisfy transcoding - request_init = {} + # 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["membership"][field])): + del request_init["membership"][field][i][subfield] + else: + del request_init["membership"][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 = space.Space( + return_value = gc_membership.Membership( name="name_value", - type_=space.Space.Type.ROOM, - space_type=space.Space.SpaceType.SPACE, - single_user_bot_dm=True, - threaded=True, - display_name="display_name_value", - external_user_allowed=True, - space_threading_state=space.Space.SpaceThreadingState.THREADED_MESSAGES, - space_history_state=history_state.HistoryState.HISTORY_OFF, - import_mode=True, - admin_installed=True, - customer="customer_value", - space_uri="space_uri_value", - predefined_permission_settings=space.Space.PredefinedPermissionSettings.COLLABORATION_SPACE, + state=gc_membership.Membership.MembershipState.JOINED, + role=gc_membership.Membership.MembershipRole.ROLE_MEMBER, ) # Wrap the value into a proper Response obj @@ -25110,35 +30343,22 @@ def test_set_up_space_rest_call_success(request_type): response_value.status_code = 200 # Convert return value to protobuf type - return_value = space.Space.pb(return_value) + return_value = gc_membership.Membership.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value.content = json_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_space(request) + response = client.create_membership(request) # Establish that the response is the type that we expect. - assert isinstance(response, space.Space) + assert isinstance(response, gc_membership.Membership) assert response.name == "name_value" - assert response.type_ == space.Space.Type.ROOM - assert response.space_type == space.Space.SpaceType.SPACE - assert response.single_user_bot_dm is True - assert response.threaded is True - assert response.display_name == "display_name_value" - assert response.external_user_allowed is True - assert ( - response.space_threading_state - == space.Space.SpaceThreadingState.THREADED_MESSAGES - ) - assert response.space_history_state == history_state.HistoryState.HISTORY_OFF - assert response.import_mode is True - assert response.admin_installed is True - assert response.customer == "customer_value" - assert response.space_uri == "space_uri_value" + assert response.state == gc_membership.Membership.MembershipState.JOINED + assert response.role == gc_membership.Membership.MembershipRole.ROLE_MEMBER @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_set_up_space_rest_interceptors(null_interceptor): +def test_create_membership_rest_interceptors(null_interceptor): transport = transports.ChatServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -25151,19 +30371,22 @@ def test_set_up_space_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.ChatServiceRestInterceptor, "post_set_up_space" + transports.ChatServiceRestInterceptor, "post_create_membership" ) as post, mock.patch.object( - transports.ChatServiceRestInterceptor, "post_set_up_space_with_metadata" + transports.ChatServiceRestInterceptor, + "post_create_membership_with_metadata", ) as post_with_metadata, mock.patch.object( - transports.ChatServiceRestInterceptor, "pre_set_up_space" + transports.ChatServiceRestInterceptor, "pre_create_membership" ) as pre, ): pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = space_setup.SetUpSpaceRequest.pb(space_setup.SetUpSpaceRequest()) + pb_message = gc_membership.CreateMembershipRequest.pb( + gc_membership.CreateMembershipRequest() + ) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -25174,19 +30397,19 @@ def test_set_up_space_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 = space.Space.to_json(space.Space()) + return_value = gc_membership.Membership.to_json(gc_membership.Membership()) req.return_value.content = return_value - request = space_setup.SetUpSpaceRequest() + request = gc_membership.CreateMembershipRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = space.Space() - post_with_metadata.return_value = space.Space(), metadata + post.return_value = gc_membership.Membership() + post_with_metadata.return_value = gc_membership.Membership(), metadata - client.set_up_space( + client.create_membership( request, metadata=[ ("key", "val"), @@ -25199,12 +30422,14 @@ def test_set_up_space_rest_interceptors(null_interceptor): post_with_metadata.assert_called_once() -def test_update_space_rest_bad_request(request_type=gc_space.UpdateSpaceRequest): +def test_update_membership_rest_bad_request( + request_type=gc_membership.UpdateMembershipRequest, +): client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {"space": {"name": "spaces/sample1"}} + request_init = {"membership": {"name": "spaces/sample1/members/sample2"}} request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -25220,71 +30445,44 @@ def test_update_space_rest_bad_request(request_type=gc_space.UpdateSpaceRequest) response_value.request = mock.Mock() req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.update_space(request) + client.update_membership(request) @pytest.mark.parametrize( "request_type", [ - gc_space.UpdateSpaceRequest, + gc_membership.UpdateMembershipRequest, dict, ], ) -def test_update_space_rest_call_success(request_type): +def test_update_membership_rest_call_success(request_type): client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {"space": {"name": "spaces/sample1"}} - request_init["space"] = { - "name": "spaces/sample1", - "type_": 1, - "space_type": 1, - "single_user_bot_dm": True, - "threaded": True, - "display_name": "display_name_value", - "external_user_allowed": True, - "space_threading_state": 2, - "space_details": { - "description": "description_value", - "guidelines": "guidelines_value", + request_init = {"membership": {"name": "spaces/sample1/members/sample2"}} + request_init["membership"] = { + "name": "spaces/sample1/members/sample2", + "state": 1, + "role": 1, + "member": { + "name": "name_value", + "display_name": "display_name_value", + "domain_id": "domain_id_value", + "type_": 1, + "is_anonymous": True, }, - "space_history_state": 1, - "import_mode": True, + "group_member": {"name": "name_value"}, "create_time": {"seconds": 751, "nanos": 543}, - "last_active_time": {}, - "admin_installed": True, - "membership_count": { - "joined_direct_human_user_count": 3185, - "joined_group_count": 1933, - }, - "access_settings": {"access_state": 1, "audience": "audience_value"}, - "customer": "customer_value", - "space_uri": "space_uri_value", - "predefined_permission_settings": 1, - "permission_settings": { - "manage_members_and_groups": { - "managers_allowed": True, - "assistant_managers_allowed": True, - "members_allowed": True, - }, - "modify_space_details": {}, - "toggle_history": {}, - "use_at_mention_all": {}, - "manage_apps": {}, - "manage_webhooks": {}, - "post_messages": {}, - "reply_messages": {}, - }, - "import_mode_expire_time": {}, + "delete_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 = gc_space.UpdateSpaceRequest.meta.fields["space"] + test_field = gc_membership.UpdateMembershipRequest.meta.fields["membership"] def get_message_fields(field): # Given a field which is a message (composite type), return a list with @@ -25312,7 +30510,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["space"].items(): # pragma: NO COVER + for field, value in request_init["membership"].items(): # pragma: NO COVER result = None is_repeated = False # For repeated fields @@ -25342,30 +30540,19 @@ def get_message_fields(field): subfield = subfield_to_delete.get("subfield") if subfield: if field_repeated: - for i in range(0, len(request_init["space"][field])): - del request_init["space"][field][i][subfield] + for i in range(0, len(request_init["membership"][field])): + del request_init["membership"][field][i][subfield] else: - del request_init["space"][field][subfield] + del request_init["membership"][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 = gc_space.Space( + return_value = gc_membership.Membership( name="name_value", - type_=gc_space.Space.Type.ROOM, - space_type=gc_space.Space.SpaceType.SPACE, - single_user_bot_dm=True, - threaded=True, - display_name="display_name_value", - external_user_allowed=True, - space_threading_state=gc_space.Space.SpaceThreadingState.THREADED_MESSAGES, - space_history_state=history_state.HistoryState.HISTORY_OFF, - import_mode=True, - admin_installed=True, - customer="customer_value", - space_uri="space_uri_value", - predefined_permission_settings=gc_space.Space.PredefinedPermissionSettings.COLLABORATION_SPACE, + state=gc_membership.Membership.MembershipState.JOINED, + role=gc_membership.Membership.MembershipRole.ROLE_MEMBER, ) # Wrap the value into a proper Response obj @@ -25373,35 +30560,22 @@ def get_message_fields(field): response_value.status_code = 200 # Convert return value to protobuf type - return_value = gc_space.Space.pb(return_value) + return_value = gc_membership.Membership.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value.content = json_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_space(request) + response = client.update_membership(request) # Establish that the response is the type that we expect. - assert isinstance(response, gc_space.Space) + assert isinstance(response, gc_membership.Membership) assert response.name == "name_value" - assert response.type_ == gc_space.Space.Type.ROOM - assert response.space_type == gc_space.Space.SpaceType.SPACE - assert response.single_user_bot_dm is True - assert response.threaded is True - assert response.display_name == "display_name_value" - assert response.external_user_allowed is True - assert ( - response.space_threading_state - == gc_space.Space.SpaceThreadingState.THREADED_MESSAGES - ) - assert response.space_history_state == history_state.HistoryState.HISTORY_OFF - assert response.import_mode is True - assert response.admin_installed is True - assert response.customer == "customer_value" - assert response.space_uri == "space_uri_value" + assert response.state == gc_membership.Membership.MembershipState.JOINED + assert response.role == gc_membership.Membership.MembershipRole.ROLE_MEMBER @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_update_space_rest_interceptors(null_interceptor): +def test_update_membership_rest_interceptors(null_interceptor): transport = transports.ChatServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -25414,19 +30588,22 @@ def test_update_space_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.ChatServiceRestInterceptor, "post_update_space" + transports.ChatServiceRestInterceptor, "post_update_membership" ) as post, mock.patch.object( - transports.ChatServiceRestInterceptor, "post_update_space_with_metadata" + transports.ChatServiceRestInterceptor, + "post_update_membership_with_metadata", ) as post_with_metadata, mock.patch.object( - transports.ChatServiceRestInterceptor, "pre_update_space" + transports.ChatServiceRestInterceptor, "pre_update_membership" ) as pre, ): pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = gc_space.UpdateSpaceRequest.pb(gc_space.UpdateSpaceRequest()) + pb_message = gc_membership.UpdateMembershipRequest.pb( + gc_membership.UpdateMembershipRequest() + ) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -25437,19 +30614,19 @@ def test_update_space_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 = gc_space.Space.to_json(gc_space.Space()) + return_value = gc_membership.Membership.to_json(gc_membership.Membership()) req.return_value.content = return_value - request = gc_space.UpdateSpaceRequest() + request = gc_membership.UpdateMembershipRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = gc_space.Space() - post_with_metadata.return_value = gc_space.Space(), metadata + post.return_value = gc_membership.Membership() + post_with_metadata.return_value = gc_membership.Membership(), metadata - client.update_space( + client.update_membership( request, metadata=[ ("key", "val"), @@ -25462,12 +30639,14 @@ def test_update_space_rest_interceptors(null_interceptor): post_with_metadata.assert_called_once() -def test_delete_space_rest_bad_request(request_type=space.DeleteSpaceRequest): +def test_delete_membership_rest_bad_request( + request_type=membership.DeleteMembershipRequest, +): client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {"name": "spaces/sample1"} + request_init = {"name": "spaces/sample1/members/sample2"} request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -25483,45 +30662,55 @@ def test_delete_space_rest_bad_request(request_type=space.DeleteSpaceRequest): response_value.request = mock.Mock() req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.delete_space(request) + client.delete_membership(request) @pytest.mark.parametrize( "request_type", [ - space.DeleteSpaceRequest, + membership.DeleteMembershipRequest, dict, ], ) -def test_delete_space_rest_call_success(request_type): +def test_delete_membership_rest_call_success(request_type): client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {"name": "spaces/sample1"} + request_init = {"name": "spaces/sample1/members/sample2"} request = request_type(**request_init) # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = None + return_value = membership.Membership( + name="name_value", + state=membership.Membership.MembershipState.JOINED, + role=membership.Membership.MembershipRole.ROLE_MEMBER, + ) # Wrap the value into a proper Response obj response_value = mock.Mock() response_value.status_code = 200 - json_return_value = "" + + # Convert return value to protobuf type + return_value = membership.Membership.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) response_value.content = json_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_space(request) + response = client.delete_membership(request) # Establish that the response is the type that we expect. - assert response is None + assert isinstance(response, membership.Membership) + assert response.name == "name_value" + assert response.state == membership.Membership.MembershipState.JOINED + assert response.role == membership.Membership.MembershipRole.ROLE_MEMBER @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_delete_space_rest_interceptors(null_interceptor): +def test_delete_membership_rest_interceptors(null_interceptor): transport = transports.ChatServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -25534,11 +30723,22 @@ def test_delete_space_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.ChatServiceRestInterceptor, "pre_delete_space" + transports.ChatServiceRestInterceptor, "post_delete_membership" + ) as post, + mock.patch.object( + transports.ChatServiceRestInterceptor, + "post_delete_membership_with_metadata", + ) as post_with_metadata, + mock.patch.object( + transports.ChatServiceRestInterceptor, "pre_delete_membership" ) as pre, ): pre.assert_not_called() - pb_message = space.DeleteSpaceRequest.pb(space.DeleteSpaceRequest()) + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = membership.DeleteMembershipRequest.pb( + membership.DeleteMembershipRequest() + ) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -25549,15 +30749,19 @@ def test_delete_space_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 = membership.Membership.to_json(membership.Membership()) + req.return_value.content = return_value - request = space.DeleteSpaceRequest() + request = membership.DeleteMembershipRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata + post.return_value = membership.Membership() + post_with_metadata.return_value = membership.Membership(), metadata - client.delete_space( + client.delete_membership( request, metadata=[ ("key", "val"), @@ -25566,16 +30770,18 @@ def test_delete_space_rest_interceptors(null_interceptor): ) pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() -def test_complete_import_space_rest_bad_request( - request_type=space.CompleteImportSpaceRequest, +def test_create_reaction_rest_bad_request( + request_type=gc_reaction.CreateReactionRequest, ): client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {"name": "spaces/sample1"} + request_init = {"parent": "spaces/sample1/messages/sample2"} request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -25591,48 +30797,141 @@ def test_complete_import_space_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.complete_import_space(request) + client.create_reaction(request) @pytest.mark.parametrize( "request_type", [ - space.CompleteImportSpaceRequest, + gc_reaction.CreateReactionRequest, dict, ], ) -def test_complete_import_space_rest_call_success(request_type): +def test_create_reaction_rest_call_success(request_type): client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {"name": "spaces/sample1"} + request_init = {"parent": "spaces/sample1/messages/sample2"} + request_init["reaction"] = { + "name": "name_value", + "user": { + "name": "name_value", + "display_name": "display_name_value", + "domain_id": "domain_id_value", + "type_": 1, + "is_anonymous": True, + }, + "emoji": { + "unicode": "unicode_value", + "custom_emoji": { + "name": "name_value", + "uid": "uid_value", + "emoji_name": "emoji_name_value", + "temporary_image_uri": "temporary_image_uri_value", + "payload": { + "file_content": b"file_content_blob", + "filename": "filename_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 = gc_reaction.CreateReactionRequest.meta.fields["reaction"] + + 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["reaction"].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["reaction"][field])): + del request_init["reaction"][field][i][subfield] + else: + del request_init["reaction"][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 = space.CompleteImportSpaceResponse() + return_value = gc_reaction.Reaction( + 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 = space.CompleteImportSpaceResponse.pb(return_value) + return_value = gc_reaction.Reaction.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value.content = json_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_import_space(request) + response = client.create_reaction(request) # Establish that the response is the type that we expect. - assert isinstance(response, space.CompleteImportSpaceResponse) + assert isinstance(response, gc_reaction.Reaction) + assert response.name == "name_value" @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_complete_import_space_rest_interceptors(null_interceptor): +def test_create_reaction_rest_interceptors(null_interceptor): transport = transports.ChatServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -25645,21 +30944,20 @@ def test_complete_import_space_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.ChatServiceRestInterceptor, "post_complete_import_space" + transports.ChatServiceRestInterceptor, "post_create_reaction" ) as post, mock.patch.object( - transports.ChatServiceRestInterceptor, - "post_complete_import_space_with_metadata", + transports.ChatServiceRestInterceptor, "post_create_reaction_with_metadata" ) as post_with_metadata, mock.patch.object( - transports.ChatServiceRestInterceptor, "pre_complete_import_space" + transports.ChatServiceRestInterceptor, "pre_create_reaction" ) as pre, ): pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = space.CompleteImportSpaceRequest.pb( - space.CompleteImportSpaceRequest() + pb_message = gc_reaction.CreateReactionRequest.pb( + gc_reaction.CreateReactionRequest() ) transcode.return_value = { "method": "post", @@ -25671,21 +30969,19 @@ def test_complete_import_space_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 = space.CompleteImportSpaceResponse.to_json( - space.CompleteImportSpaceResponse() - ) + return_value = gc_reaction.Reaction.to_json(gc_reaction.Reaction()) req.return_value.content = return_value - request = space.CompleteImportSpaceRequest() + request = gc_reaction.CreateReactionRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = space.CompleteImportSpaceResponse() - post_with_metadata.return_value = space.CompleteImportSpaceResponse(), metadata + post.return_value = gc_reaction.Reaction() + post_with_metadata.return_value = gc_reaction.Reaction(), metadata - client.complete_import_space( + client.create_reaction( request, metadata=[ ("key", "val"), @@ -25698,14 +30994,12 @@ def test_complete_import_space_rest_interceptors(null_interceptor): post_with_metadata.assert_called_once() -def test_find_direct_message_rest_bad_request( - request_type=space.FindDirectMessageRequest, -): +def test_list_reactions_rest_bad_request(request_type=reaction.ListReactionsRequest): client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {} + request_init = {"parent": "spaces/sample1/messages/sample2"} request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -25721,43 +31015,30 @@ def test_find_direct_message_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.find_direct_message(request) + client.list_reactions(request) @pytest.mark.parametrize( "request_type", [ - space.FindDirectMessageRequest, + reaction.ListReactionsRequest, dict, ], ) -def test_find_direct_message_rest_call_success(request_type): +def test_list_reactions_rest_call_success(request_type): client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {} + request_init = {"parent": "spaces/sample1/messages/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 = space.Space( - name="name_value", - type_=space.Space.Type.ROOM, - space_type=space.Space.SpaceType.SPACE, - single_user_bot_dm=True, - threaded=True, - display_name="display_name_value", - external_user_allowed=True, - space_threading_state=space.Space.SpaceThreadingState.THREADED_MESSAGES, - space_history_state=history_state.HistoryState.HISTORY_OFF, - import_mode=True, - admin_installed=True, - customer="customer_value", - space_uri="space_uri_value", - predefined_permission_settings=space.Space.PredefinedPermissionSettings.COLLABORATION_SPACE, + return_value = reaction.ListReactionsResponse( + next_page_token="next_page_token_value", ) # Wrap the value into a proper Response obj @@ -25765,35 +31046,20 @@ def test_find_direct_message_rest_call_success(request_type): response_value.status_code = 200 # Convert return value to protobuf type - return_value = space.Space.pb(return_value) + return_value = reaction.ListReactionsResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.find_direct_message(request) + response = client.list_reactions(request) # Establish that the response is the type that we expect. - assert isinstance(response, space.Space) - assert response.name == "name_value" - assert response.type_ == space.Space.Type.ROOM - assert response.space_type == space.Space.SpaceType.SPACE - assert response.single_user_bot_dm is True - assert response.threaded is True - assert response.display_name == "display_name_value" - assert response.external_user_allowed is True - assert ( - response.space_threading_state - == space.Space.SpaceThreadingState.THREADED_MESSAGES - ) - assert response.space_history_state == history_state.HistoryState.HISTORY_OFF - assert response.import_mode is True - assert response.admin_installed is True - assert response.customer == "customer_value" - assert response.space_uri == "space_uri_value" + assert isinstance(response, pagers.ListReactionsPager) + assert response.next_page_token == "next_page_token_value" @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_find_direct_message_rest_interceptors(null_interceptor): +def test_list_reactions_rest_interceptors(null_interceptor): transport = transports.ChatServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -25806,20 +31072,19 @@ def test_find_direct_message_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.ChatServiceRestInterceptor, "post_find_direct_message" + transports.ChatServiceRestInterceptor, "post_list_reactions" ) as post, mock.patch.object( - transports.ChatServiceRestInterceptor, - "post_find_direct_message_with_metadata", + transports.ChatServiceRestInterceptor, "post_list_reactions_with_metadata" ) as post_with_metadata, mock.patch.object( - transports.ChatServiceRestInterceptor, "pre_find_direct_message" + transports.ChatServiceRestInterceptor, "pre_list_reactions" ) as pre, ): pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = space.FindDirectMessageRequest.pb(space.FindDirectMessageRequest()) + pb_message = reaction.ListReactionsRequest.pb(reaction.ListReactionsRequest()) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -25830,19 +31095,21 @@ def test_find_direct_message_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 = space.Space.to_json(space.Space()) + return_value = reaction.ListReactionsResponse.to_json( + reaction.ListReactionsResponse() + ) req.return_value.content = return_value - request = space.FindDirectMessageRequest() + request = reaction.ListReactionsRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = space.Space() - post_with_metadata.return_value = space.Space(), metadata + post.return_value = reaction.ListReactionsResponse() + post_with_metadata.return_value = reaction.ListReactionsResponse(), metadata - client.find_direct_message( + client.list_reactions( request, metadata=[ ("key", "val"), @@ -25855,14 +31122,12 @@ def test_find_direct_message_rest_interceptors(null_interceptor): post_with_metadata.assert_called_once() -def test_create_membership_rest_bad_request( - request_type=gc_membership.CreateMembershipRequest, -): +def test_delete_reaction_rest_bad_request(request_type=reaction.DeleteReactionRequest): client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {"parent": "spaces/sample1"} + request_init = {"name": "spaces/sample1/messages/sample2/reactions/sample3"} request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -25878,137 +31143,45 @@ def test_create_membership_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_membership(request) + client.delete_reaction(request) @pytest.mark.parametrize( "request_type", [ - gc_membership.CreateMembershipRequest, + reaction.DeleteReactionRequest, dict, ], ) -def test_create_membership_rest_call_success(request_type): +def test_delete_reaction_rest_call_success(request_type): client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {"parent": "spaces/sample1"} - request_init["membership"] = { - "name": "name_value", - "state": 1, - "role": 1, - "member": { - "name": "name_value", - "display_name": "display_name_value", - "domain_id": "domain_id_value", - "type_": 1, - "is_anonymous": True, - }, - "group_member": {"name": "name_value"}, - "create_time": {"seconds": 751, "nanos": 543}, - "delete_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 = gc_membership.CreateMembershipRequest.meta.fields["membership"] - - 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["membership"].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["membership"][field])): - del request_init["membership"][field][i][subfield] - else: - del request_init["membership"][field][subfield] + request_init = {"name": "spaces/sample1/messages/sample2/reactions/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 = gc_membership.Membership( - name="name_value", - state=gc_membership.Membership.MembershipState.JOINED, - role=gc_membership.Membership.MembershipRole.ROLE_MEMBER, - ) + return_value = None # Wrap the value into a proper Response obj response_value = mock.Mock() response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = gc_membership.Membership.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) + json_return_value = "" response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.create_membership(request) + response = client.delete_reaction(request) # Establish that the response is the type that we expect. - assert isinstance(response, gc_membership.Membership) - assert response.name == "name_value" - assert response.state == gc_membership.Membership.MembershipState.JOINED - assert response.role == gc_membership.Membership.MembershipRole.ROLE_MEMBER + assert response is None @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_create_membership_rest_interceptors(null_interceptor): +def test_delete_reaction_rest_interceptors(null_interceptor): transport = transports.ChatServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -26021,22 +31194,11 @@ def test_create_membership_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.ChatServiceRestInterceptor, "post_create_membership" - ) as post, - mock.patch.object( - transports.ChatServiceRestInterceptor, - "post_create_membership_with_metadata", - ) as post_with_metadata, - mock.patch.object( - transports.ChatServiceRestInterceptor, "pre_create_membership" + transports.ChatServiceRestInterceptor, "pre_delete_reaction" ) as pre, ): pre.assert_not_called() - post.assert_not_called() - post_with_metadata.assert_not_called() - pb_message = gc_membership.CreateMembershipRequest.pb( - gc_membership.CreateMembershipRequest() - ) + pb_message = reaction.DeleteReactionRequest.pb(reaction.DeleteReactionRequest()) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -26047,19 +31209,15 @@ def test_create_membership_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 = gc_membership.Membership.to_json(gc_membership.Membership()) - req.return_value.content = return_value - request = gc_membership.CreateMembershipRequest() + request = reaction.DeleteReactionRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = gc_membership.Membership() - post_with_metadata.return_value = gc_membership.Membership(), metadata - client.create_membership( + client.delete_reaction( request, metadata=[ ("key", "val"), @@ -26068,18 +31226,16 @@ def test_create_membership_rest_interceptors(null_interceptor): ) pre.assert_called_once() - post.assert_called_once() - post_with_metadata.assert_called_once() -def test_update_membership_rest_bad_request( - request_type=gc_membership.UpdateMembershipRequest, +def test_create_custom_emoji_rest_bad_request( + request_type=reaction.CreateCustomEmojiRequest, ): client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {"membership": {"name": "spaces/sample1/members/sample2"}} + request_init = {} request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -26095,44 +31251,36 @@ def test_update_membership_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_membership(request) + client.create_custom_emoji(request) @pytest.mark.parametrize( "request_type", [ - gc_membership.UpdateMembershipRequest, + reaction.CreateCustomEmojiRequest, dict, ], ) -def test_update_membership_rest_call_success(request_type): +def test_create_custom_emoji_rest_call_success(request_type): client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {"membership": {"name": "spaces/sample1/members/sample2"}} - request_init["membership"] = { - "name": "spaces/sample1/members/sample2", - "state": 1, - "role": 1, - "member": { - "name": "name_value", - "display_name": "display_name_value", - "domain_id": "domain_id_value", - "type_": 1, - "is_anonymous": True, - }, - "group_member": {"name": "name_value"}, - "create_time": {"seconds": 751, "nanos": 543}, - "delete_time": {}, + request_init = {} + request_init["custom_emoji"] = { + "name": "name_value", + "uid": "uid_value", + "emoji_name": "emoji_name_value", + "temporary_image_uri": "temporary_image_uri_value", + "payload": {"file_content": b"file_content_blob", "filename": "filename_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 = gc_membership.UpdateMembershipRequest.meta.fields["membership"] + test_field = reaction.CreateCustomEmojiRequest.meta.fields["custom_emoji"] def get_message_fields(field): # Given a field which is a message (composite type), return a list with @@ -26160,7 +31308,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["membership"].items(): # pragma: NO COVER + for field, value in request_init["custom_emoji"].items(): # pragma: NO COVER result = None is_repeated = False # For repeated fields @@ -26190,19 +31338,20 @@ def get_message_fields(field): subfield = subfield_to_delete.get("subfield") if subfield: if field_repeated: - for i in range(0, len(request_init["membership"][field])): - del request_init["membership"][field][i][subfield] + for i in range(0, len(request_init["custom_emoji"][field])): + del request_init["custom_emoji"][field][i][subfield] else: - del request_init["membership"][field][subfield] + del request_init["custom_emoji"][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 = gc_membership.Membership( + return_value = reaction.CustomEmoji( name="name_value", - state=gc_membership.Membership.MembershipState.JOINED, - role=gc_membership.Membership.MembershipRole.ROLE_MEMBER, + uid="uid_value", + emoji_name="emoji_name_value", + temporary_image_uri="temporary_image_uri_value", ) # Wrap the value into a proper Response obj @@ -26210,22 +31359,23 @@ def get_message_fields(field): response_value.status_code = 200 # Convert return value to protobuf type - return_value = gc_membership.Membership.pb(return_value) + return_value = reaction.CustomEmoji.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value.content = json_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_membership(request) + response = client.create_custom_emoji(request) # Establish that the response is the type that we expect. - assert isinstance(response, gc_membership.Membership) + assert isinstance(response, reaction.CustomEmoji) assert response.name == "name_value" - assert response.state == gc_membership.Membership.MembershipState.JOINED - assert response.role == gc_membership.Membership.MembershipRole.ROLE_MEMBER + assert response.uid == "uid_value" + assert response.emoji_name == "emoji_name_value" + assert response.temporary_image_uri == "temporary_image_uri_value" @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_update_membership_rest_interceptors(null_interceptor): +def test_create_custom_emoji_rest_interceptors(null_interceptor): transport = transports.ChatServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -26238,21 +31388,21 @@ def test_update_membership_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.ChatServiceRestInterceptor, "post_update_membership" + transports.ChatServiceRestInterceptor, "post_create_custom_emoji" ) as post, mock.patch.object( transports.ChatServiceRestInterceptor, - "post_update_membership_with_metadata", + "post_create_custom_emoji_with_metadata", ) as post_with_metadata, mock.patch.object( - transports.ChatServiceRestInterceptor, "pre_update_membership" + transports.ChatServiceRestInterceptor, "pre_create_custom_emoji" ) as pre, ): pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = gc_membership.UpdateMembershipRequest.pb( - gc_membership.UpdateMembershipRequest() + pb_message = reaction.CreateCustomEmojiRequest.pb( + reaction.CreateCustomEmojiRequest() ) transcode.return_value = { "method": "post", @@ -26264,19 +31414,19 @@ def test_update_membership_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 = gc_membership.Membership.to_json(gc_membership.Membership()) + return_value = reaction.CustomEmoji.to_json(reaction.CustomEmoji()) req.return_value.content = return_value - request = gc_membership.UpdateMembershipRequest() + request = reaction.CreateCustomEmojiRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = gc_membership.Membership() - post_with_metadata.return_value = gc_membership.Membership(), metadata + post.return_value = reaction.CustomEmoji() + post_with_metadata.return_value = reaction.CustomEmoji(), metadata - client.update_membership( + client.create_custom_emoji( request, metadata=[ ("key", "val"), @@ -26289,14 +31439,12 @@ def test_update_membership_rest_interceptors(null_interceptor): post_with_metadata.assert_called_once() -def test_delete_membership_rest_bad_request( - request_type=membership.DeleteMembershipRequest, -): +def test_get_custom_emoji_rest_bad_request(request_type=reaction.GetCustomEmojiRequest): client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {"name": "spaces/sample1/members/sample2"} + request_init = {"name": "customEmojis/sample1"} request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -26312,32 +31460,33 @@ def test_delete_membership_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_membership(request) + client.get_custom_emoji(request) @pytest.mark.parametrize( "request_type", [ - membership.DeleteMembershipRequest, + reaction.GetCustomEmojiRequest, dict, ], ) -def test_delete_membership_rest_call_success(request_type): +def test_get_custom_emoji_rest_call_success(request_type): client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {"name": "spaces/sample1/members/sample2"} + request_init = {"name": "customEmojis/sample1"} request = request_type(**request_init) # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = membership.Membership( + return_value = reaction.CustomEmoji( name="name_value", - state=membership.Membership.MembershipState.JOINED, - role=membership.Membership.MembershipRole.ROLE_MEMBER, + uid="uid_value", + emoji_name="emoji_name_value", + temporary_image_uri="temporary_image_uri_value", ) # Wrap the value into a proper Response obj @@ -26345,22 +31494,23 @@ def test_delete_membership_rest_call_success(request_type): response_value.status_code = 200 # Convert return value to protobuf type - return_value = membership.Membership.pb(return_value) + return_value = reaction.CustomEmoji.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value.content = json_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_membership(request) + response = client.get_custom_emoji(request) # Establish that the response is the type that we expect. - assert isinstance(response, membership.Membership) + assert isinstance(response, reaction.CustomEmoji) assert response.name == "name_value" - assert response.state == membership.Membership.MembershipState.JOINED - assert response.role == membership.Membership.MembershipRole.ROLE_MEMBER + assert response.uid == "uid_value" + assert response.emoji_name == "emoji_name_value" + assert response.temporary_image_uri == "temporary_image_uri_value" @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_delete_membership_rest_interceptors(null_interceptor): +def test_get_custom_emoji_rest_interceptors(null_interceptor): transport = transports.ChatServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -26373,22 +31523,19 @@ def test_delete_membership_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.ChatServiceRestInterceptor, "post_delete_membership" + transports.ChatServiceRestInterceptor, "post_get_custom_emoji" ) as post, mock.patch.object( - transports.ChatServiceRestInterceptor, - "post_delete_membership_with_metadata", + transports.ChatServiceRestInterceptor, "post_get_custom_emoji_with_metadata" ) as post_with_metadata, mock.patch.object( - transports.ChatServiceRestInterceptor, "pre_delete_membership" + transports.ChatServiceRestInterceptor, "pre_get_custom_emoji" ) as pre, ): pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = membership.DeleteMembershipRequest.pb( - membership.DeleteMembershipRequest() - ) + pb_message = reaction.GetCustomEmojiRequest.pb(reaction.GetCustomEmojiRequest()) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -26399,19 +31546,19 @@ def test_delete_membership_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 = membership.Membership.to_json(membership.Membership()) + return_value = reaction.CustomEmoji.to_json(reaction.CustomEmoji()) req.return_value.content = return_value - request = membership.DeleteMembershipRequest() + request = reaction.GetCustomEmojiRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = membership.Membership() - post_with_metadata.return_value = membership.Membership(), metadata + post.return_value = reaction.CustomEmoji() + post_with_metadata.return_value = reaction.CustomEmoji(), metadata - client.delete_membership( + client.get_custom_emoji( request, metadata=[ ("key", "val"), @@ -26424,14 +31571,14 @@ def test_delete_membership_rest_interceptors(null_interceptor): post_with_metadata.assert_called_once() -def test_create_reaction_rest_bad_request( - request_type=gc_reaction.CreateReactionRequest, +def test_list_custom_emojis_rest_bad_request( + request_type=reaction.ListCustomEmojisRequest, ): client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {"parent": "spaces/sample1/messages/sample2"} + request_init = {} request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -26447,120 +31594,30 @@ def test_create_reaction_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_reaction(request) + client.list_custom_emojis(request) @pytest.mark.parametrize( "request_type", [ - gc_reaction.CreateReactionRequest, + reaction.ListCustomEmojisRequest, dict, ], ) -def test_create_reaction_rest_call_success(request_type): +def test_list_custom_emojis_rest_call_success(request_type): client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {"parent": "spaces/sample1/messages/sample2"} - request_init["reaction"] = { - "name": "name_value", - "user": { - "name": "name_value", - "display_name": "display_name_value", - "domain_id": "domain_id_value", - "type_": 1, - "is_anonymous": True, - }, - "emoji": { - "unicode": "unicode_value", - "custom_emoji": { - "name": "name_value", - "uid": "uid_value", - "emoji_name": "emoji_name_value", - "temporary_image_uri": "temporary_image_uri_value", - "payload": { - "file_content": b"file_content_blob", - "filename": "filename_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 = gc_reaction.CreateReactionRequest.meta.fields["reaction"] - - 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["reaction"].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["reaction"][field])): - del request_init["reaction"][field][i][subfield] - else: - del request_init["reaction"][field][subfield] + request_init = {} request = request_type(**request_init) # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = gc_reaction.Reaction( - name="name_value", + return_value = reaction.ListCustomEmojisResponse( + next_page_token="next_page_token_value", ) # Wrap the value into a proper Response obj @@ -26568,20 +31625,20 @@ def get_message_fields(field): response_value.status_code = 200 # Convert return value to protobuf type - return_value = gc_reaction.Reaction.pb(return_value) + return_value = reaction.ListCustomEmojisResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value.content = json_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_reaction(request) + response = client.list_custom_emojis(request) # Establish that the response is the type that we expect. - assert isinstance(response, gc_reaction.Reaction) - assert response.name == "name_value" + assert isinstance(response, pagers.ListCustomEmojisPager) + assert response.next_page_token == "next_page_token_value" @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_create_reaction_rest_interceptors(null_interceptor): +def test_list_custom_emojis_rest_interceptors(null_interceptor): transport = transports.ChatServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -26594,20 +31651,21 @@ def test_create_reaction_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.ChatServiceRestInterceptor, "post_create_reaction" + transports.ChatServiceRestInterceptor, "post_list_custom_emojis" ) as post, mock.patch.object( - transports.ChatServiceRestInterceptor, "post_create_reaction_with_metadata" + transports.ChatServiceRestInterceptor, + "post_list_custom_emojis_with_metadata", ) as post_with_metadata, mock.patch.object( - transports.ChatServiceRestInterceptor, "pre_create_reaction" + transports.ChatServiceRestInterceptor, "pre_list_custom_emojis" ) as pre, ): pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = gc_reaction.CreateReactionRequest.pb( - gc_reaction.CreateReactionRequest() + pb_message = reaction.ListCustomEmojisRequest.pb( + reaction.ListCustomEmojisRequest() ) transcode.return_value = { "method": "post", @@ -26619,19 +31677,21 @@ def test_create_reaction_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 = gc_reaction.Reaction.to_json(gc_reaction.Reaction()) + return_value = reaction.ListCustomEmojisResponse.to_json( + reaction.ListCustomEmojisResponse() + ) req.return_value.content = return_value - request = gc_reaction.CreateReactionRequest() + request = reaction.ListCustomEmojisRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = gc_reaction.Reaction() - post_with_metadata.return_value = gc_reaction.Reaction(), metadata + post.return_value = reaction.ListCustomEmojisResponse() + post_with_metadata.return_value = reaction.ListCustomEmojisResponse(), metadata - client.create_reaction( + client.list_custom_emojis( request, metadata=[ ("key", "val"), @@ -26644,12 +31704,14 @@ def test_create_reaction_rest_interceptors(null_interceptor): post_with_metadata.assert_called_once() -def test_list_reactions_rest_bad_request(request_type=reaction.ListReactionsRequest): +def test_delete_custom_emoji_rest_bad_request( + request_type=reaction.DeleteCustomEmojiRequest, +): client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {"parent": "spaces/sample1/messages/sample2"} + request_init = {"name": "customEmojis/sample1"} request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -26665,51 +31727,45 @@ def test_list_reactions_rest_bad_request(request_type=reaction.ListReactionsRequ response_value.request = mock.Mock() req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.list_reactions(request) + client.delete_custom_emoji(request) @pytest.mark.parametrize( "request_type", [ - reaction.ListReactionsRequest, + reaction.DeleteCustomEmojiRequest, dict, ], ) -def test_list_reactions_rest_call_success(request_type): +def test_delete_custom_emoji_rest_call_success(request_type): client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {"parent": "spaces/sample1/messages/sample2"} + request_init = {"name": "customEmojis/sample1"} request = request_type(**request_init) # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = reaction.ListReactionsResponse( - next_page_token="next_page_token_value", - ) + return_value = None # Wrap the value into a proper Response obj response_value = mock.Mock() response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = reaction.ListReactionsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) + json_return_value = "" response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.list_reactions(request) + response = client.delete_custom_emoji(request) # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListReactionsPager) - assert response.next_page_token == "next_page_token_value" + assert response is None @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_reactions_rest_interceptors(null_interceptor): +def test_delete_custom_emoji_rest_interceptors(null_interceptor): transport = transports.ChatServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -26722,19 +31778,13 @@ def test_list_reactions_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.ChatServiceRestInterceptor, "post_list_reactions" - ) as post, - mock.patch.object( - transports.ChatServiceRestInterceptor, "post_list_reactions_with_metadata" - ) as post_with_metadata, - mock.patch.object( - transports.ChatServiceRestInterceptor, "pre_list_reactions" + transports.ChatServiceRestInterceptor, "pre_delete_custom_emoji" ) as pre, ): pre.assert_not_called() - post.assert_not_called() - post_with_metadata.assert_not_called() - pb_message = reaction.ListReactionsRequest.pb(reaction.ListReactionsRequest()) + pb_message = reaction.DeleteCustomEmojiRequest.pb( + reaction.DeleteCustomEmojiRequest() + ) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -26745,21 +31795,15 @@ def test_list_reactions_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 = reaction.ListReactionsResponse.to_json( - reaction.ListReactionsResponse() - ) - req.return_value.content = return_value - request = reaction.ListReactionsRequest() + request = reaction.DeleteCustomEmojiRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = reaction.ListReactionsResponse() - post_with_metadata.return_value = reaction.ListReactionsResponse(), metadata - client.list_reactions( + client.delete_custom_emoji( request, metadata=[ ("key", "val"), @@ -26768,16 +31812,16 @@ def test_list_reactions_rest_interceptors(null_interceptor): ) pre.assert_called_once() - post.assert_called_once() - post_with_metadata.assert_called_once() -def test_delete_reaction_rest_bad_request(request_type=reaction.DeleteReactionRequest): +def test_get_space_read_state_rest_bad_request( + request_type=space_read_state.GetSpaceReadStateRequest, +): client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {"name": "spaces/sample1/messages/sample2/reactions/sample3"} + request_init = {"name": "users/sample1/spaces/sample2/spaceReadState"} request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -26793,45 +31837,51 @@ def test_delete_reaction_rest_bad_request(request_type=reaction.DeleteReactionRe response_value.request = mock.Mock() req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.delete_reaction(request) + client.get_space_read_state(request) @pytest.mark.parametrize( "request_type", [ - reaction.DeleteReactionRequest, + space_read_state.GetSpaceReadStateRequest, dict, ], ) -def test_delete_reaction_rest_call_success(request_type): +def test_get_space_read_state_rest_call_success(request_type): client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {"name": "spaces/sample1/messages/sample2/reactions/sample3"} + request_init = {"name": "users/sample1/spaces/sample2/spaceReadState"} request = request_type(**request_init) # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = None + return_value = space_read_state.SpaceReadState( + name="name_value", + ) # Wrap the value into a proper Response obj response_value = mock.Mock() response_value.status_code = 200 - json_return_value = "" + + # Convert return value to protobuf type + return_value = space_read_state.SpaceReadState.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) response_value.content = json_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_reaction(request) + response = client.get_space_read_state(request) # Establish that the response is the type that we expect. - assert response is None + assert isinstance(response, space_read_state.SpaceReadState) + assert response.name == "name_value" @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_delete_reaction_rest_interceptors(null_interceptor): +def test_get_space_read_state_rest_interceptors(null_interceptor): transport = transports.ChatServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -26844,11 +31894,22 @@ def test_delete_reaction_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.ChatServiceRestInterceptor, "pre_delete_reaction" + transports.ChatServiceRestInterceptor, "post_get_space_read_state" + ) as post, + mock.patch.object( + transports.ChatServiceRestInterceptor, + "post_get_space_read_state_with_metadata", + ) as post_with_metadata, + mock.patch.object( + transports.ChatServiceRestInterceptor, "pre_get_space_read_state" ) as pre, ): pre.assert_not_called() - pb_message = reaction.DeleteReactionRequest.pb(reaction.DeleteReactionRequest()) + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = space_read_state.GetSpaceReadStateRequest.pb( + space_read_state.GetSpaceReadStateRequest() + ) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -26859,15 +31920,21 @@ def test_delete_reaction_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 = space_read_state.SpaceReadState.to_json( + space_read_state.SpaceReadState() + ) + req.return_value.content = return_value - request = reaction.DeleteReactionRequest() + request = space_read_state.GetSpaceReadStateRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata + post.return_value = space_read_state.SpaceReadState() + post_with_metadata.return_value = space_read_state.SpaceReadState(), metadata - client.delete_reaction( + client.get_space_read_state( request, metadata=[ ("key", "val"), @@ -26876,16 +31943,20 @@ def test_delete_reaction_rest_interceptors(null_interceptor): ) pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() -def test_create_custom_emoji_rest_bad_request( - request_type=reaction.CreateCustomEmojiRequest, +def test_update_space_read_state_rest_bad_request( + request_type=gc_space_read_state.UpdateSpaceReadStateRequest, ): client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {} + request_init = { + "space_read_state": {"name": "users/sample1/spaces/sample2/spaceReadState"} + } request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -26901,36 +31972,37 @@ def test_create_custom_emoji_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_custom_emoji(request) + client.update_space_read_state(request) @pytest.mark.parametrize( "request_type", [ - reaction.CreateCustomEmojiRequest, + gc_space_read_state.UpdateSpaceReadStateRequest, dict, ], ) -def test_create_custom_emoji_rest_call_success(request_type): +def test_update_space_read_state_rest_call_success(request_type): client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {} - request_init["custom_emoji"] = { - "name": "name_value", - "uid": "uid_value", - "emoji_name": "emoji_name_value", - "temporary_image_uri": "temporary_image_uri_value", - "payload": {"file_content": b"file_content_blob", "filename": "filename_value"}, + request_init = { + "space_read_state": {"name": "users/sample1/spaces/sample2/spaceReadState"} + } + request_init["space_read_state"] = { + "name": "users/sample1/spaces/sample2/spaceReadState", + "last_read_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 = reaction.CreateCustomEmojiRequest.meta.fields["custom_emoji"] + test_field = gc_space_read_state.UpdateSpaceReadStateRequest.meta.fields[ + "space_read_state" + ] def get_message_fields(field): # Given a field which is a message (composite type), return a list with @@ -26958,7 +32030,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["custom_emoji"].items(): # pragma: NO COVER + for field, value in request_init["space_read_state"].items(): # pragma: NO COVER result = None is_repeated = False # For repeated fields @@ -26988,20 +32060,17 @@ def get_message_fields(field): subfield = subfield_to_delete.get("subfield") if subfield: if field_repeated: - for i in range(0, len(request_init["custom_emoji"][field])): - del request_init["custom_emoji"][field][i][subfield] + for i in range(0, len(request_init["space_read_state"][field])): + del request_init["space_read_state"][field][i][subfield] else: - del request_init["custom_emoji"][field][subfield] + del request_init["space_read_state"][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 = reaction.CustomEmoji( + return_value = gc_space_read_state.SpaceReadState( name="name_value", - uid="uid_value", - emoji_name="emoji_name_value", - temporary_image_uri="temporary_image_uri_value", ) # Wrap the value into a proper Response obj @@ -27009,23 +32078,20 @@ def get_message_fields(field): response_value.status_code = 200 # Convert return value to protobuf type - return_value = reaction.CustomEmoji.pb(return_value) + return_value = gc_space_read_state.SpaceReadState.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value.content = json_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_custom_emoji(request) + response = client.update_space_read_state(request) # Establish that the response is the type that we expect. - assert isinstance(response, reaction.CustomEmoji) + assert isinstance(response, gc_space_read_state.SpaceReadState) assert response.name == "name_value" - assert response.uid == "uid_value" - assert response.emoji_name == "emoji_name_value" - assert response.temporary_image_uri == "temporary_image_uri_value" @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_create_custom_emoji_rest_interceptors(null_interceptor): +def test_update_space_read_state_rest_interceptors(null_interceptor): transport = transports.ChatServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -27038,21 +32104,21 @@ def test_create_custom_emoji_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.ChatServiceRestInterceptor, "post_create_custom_emoji" + transports.ChatServiceRestInterceptor, "post_update_space_read_state" ) as post, mock.patch.object( transports.ChatServiceRestInterceptor, - "post_create_custom_emoji_with_metadata", + "post_update_space_read_state_with_metadata", ) as post_with_metadata, mock.patch.object( - transports.ChatServiceRestInterceptor, "pre_create_custom_emoji" + transports.ChatServiceRestInterceptor, "pre_update_space_read_state" ) as pre, ): pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = reaction.CreateCustomEmojiRequest.pb( - reaction.CreateCustomEmojiRequest() + pb_message = gc_space_read_state.UpdateSpaceReadStateRequest.pb( + gc_space_read_state.UpdateSpaceReadStateRequest() ) transcode.return_value = { "method": "post", @@ -27064,19 +32130,21 @@ def test_create_custom_emoji_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 = reaction.CustomEmoji.to_json(reaction.CustomEmoji()) + return_value = gc_space_read_state.SpaceReadState.to_json( + gc_space_read_state.SpaceReadState() + ) req.return_value.content = return_value - request = reaction.CreateCustomEmojiRequest() + request = gc_space_read_state.UpdateSpaceReadStateRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = reaction.CustomEmoji() - post_with_metadata.return_value = reaction.CustomEmoji(), metadata + post.return_value = gc_space_read_state.SpaceReadState() + post_with_metadata.return_value = gc_space_read_state.SpaceReadState(), metadata - client.create_custom_emoji( + client.update_space_read_state( request, metadata=[ ("key", "val"), @@ -27089,12 +32157,16 @@ def test_create_custom_emoji_rest_interceptors(null_interceptor): post_with_metadata.assert_called_once() -def test_get_custom_emoji_rest_bad_request(request_type=reaction.GetCustomEmojiRequest): +def test_get_thread_read_state_rest_bad_request( + request_type=thread_read_state.GetThreadReadStateRequest, +): client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {"name": "customEmojis/sample1"} + request_init = { + "name": "users/sample1/spaces/sample2/threads/sample3/threadReadState" + } request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -27110,33 +32182,166 @@ def test_get_custom_emoji_rest_bad_request(request_type=reaction.GetCustomEmojiR response_value.request = mock.Mock() req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.get_custom_emoji(request) + client.get_thread_read_state(request) @pytest.mark.parametrize( "request_type", [ - reaction.GetCustomEmojiRequest, + thread_read_state.GetThreadReadStateRequest, dict, ], ) -def test_get_custom_emoji_rest_call_success(request_type): +def test_get_thread_read_state_rest_call_success(request_type): client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {"name": "customEmojis/sample1"} + request_init = { + "name": "users/sample1/spaces/sample2/threads/sample3/threadReadState" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = thread_read_state.ThreadReadState( + 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 = thread_read_state.ThreadReadState.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_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_thread_read_state(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, thread_read_state.ThreadReadState) + assert response.name == "name_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_thread_read_state_rest_interceptors(null_interceptor): + transport = transports.ChatServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.ChatServiceRestInterceptor(), + ) + client = ChatServiceClient(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.ChatServiceRestInterceptor, "post_get_thread_read_state" + ) as post, + mock.patch.object( + transports.ChatServiceRestInterceptor, + "post_get_thread_read_state_with_metadata", + ) as post_with_metadata, + mock.patch.object( + transports.ChatServiceRestInterceptor, "pre_get_thread_read_state" + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = thread_read_state.GetThreadReadStateRequest.pb( + thread_read_state.GetThreadReadStateRequest() + ) + 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 = thread_read_state.ThreadReadState.to_json( + thread_read_state.ThreadReadState() + ) + req.return_value.content = return_value + + request = thread_read_state.GetThreadReadStateRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = thread_read_state.ThreadReadState() + post_with_metadata.return_value = thread_read_state.ThreadReadState(), metadata + + client.get_thread_read_state( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_get_space_event_rest_bad_request( + request_type=space_event.GetSpaceEventRequest, +): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"name": "spaces/sample1/spaceEvents/sample2"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.get_space_event(request) + + +@pytest.mark.parametrize( + "request_type", + [ + space_event.GetSpaceEventRequest, + dict, + ], +) +def test_get_space_event_rest_call_success(request_type): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"name": "spaces/sample1/spaceEvents/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 = reaction.CustomEmoji( + return_value = space_event.SpaceEvent( name="name_value", - uid="uid_value", - emoji_name="emoji_name_value", - temporary_image_uri="temporary_image_uri_value", + event_type="event_type_value", ) # Wrap the value into a proper Response obj @@ -27144,23 +32349,21 @@ def test_get_custom_emoji_rest_call_success(request_type): response_value.status_code = 200 # Convert return value to protobuf type - return_value = reaction.CustomEmoji.pb(return_value) + return_value = space_event.SpaceEvent.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value.content = json_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_custom_emoji(request) + response = client.get_space_event(request) # Establish that the response is the type that we expect. - assert isinstance(response, reaction.CustomEmoji) + assert isinstance(response, space_event.SpaceEvent) assert response.name == "name_value" - assert response.uid == "uid_value" - assert response.emoji_name == "emoji_name_value" - assert response.temporary_image_uri == "temporary_image_uri_value" + assert response.event_type == "event_type_value" @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_custom_emoji_rest_interceptors(null_interceptor): +def test_get_space_event_rest_interceptors(null_interceptor): transport = transports.ChatServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -27173,19 +32376,21 @@ def test_get_custom_emoji_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.ChatServiceRestInterceptor, "post_get_custom_emoji" + transports.ChatServiceRestInterceptor, "post_get_space_event" ) as post, mock.patch.object( - transports.ChatServiceRestInterceptor, "post_get_custom_emoji_with_metadata" + transports.ChatServiceRestInterceptor, "post_get_space_event_with_metadata" ) as post_with_metadata, mock.patch.object( - transports.ChatServiceRestInterceptor, "pre_get_custom_emoji" + transports.ChatServiceRestInterceptor, "pre_get_space_event" ) as pre, ): pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = reaction.GetCustomEmojiRequest.pb(reaction.GetCustomEmojiRequest()) + pb_message = space_event.GetSpaceEventRequest.pb( + space_event.GetSpaceEventRequest() + ) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -27196,19 +32401,19 @@ def test_get_custom_emoji_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 = reaction.CustomEmoji.to_json(reaction.CustomEmoji()) + return_value = space_event.SpaceEvent.to_json(space_event.SpaceEvent()) req.return_value.content = return_value - request = reaction.GetCustomEmojiRequest() + request = space_event.GetSpaceEventRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = reaction.CustomEmoji() - post_with_metadata.return_value = reaction.CustomEmoji(), metadata + post.return_value = space_event.SpaceEvent() + post_with_metadata.return_value = space_event.SpaceEvent(), metadata - client.get_custom_emoji( + client.get_space_event( request, metadata=[ ("key", "val"), @@ -27221,14 +32426,14 @@ def test_get_custom_emoji_rest_interceptors(null_interceptor): post_with_metadata.assert_called_once() -def test_list_custom_emojis_rest_bad_request( - request_type=reaction.ListCustomEmojisRequest, +def test_list_space_events_rest_bad_request( + request_type=space_event.ListSpaceEventsRequest, ): client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {} + request_init = {"parent": "spaces/sample1"} request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -27244,29 +32449,29 @@ def test_list_custom_emojis_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_custom_emojis(request) + client.list_space_events(request) @pytest.mark.parametrize( "request_type", [ - reaction.ListCustomEmojisRequest, + space_event.ListSpaceEventsRequest, dict, ], ) -def test_list_custom_emojis_rest_call_success(request_type): +def test_list_space_events_rest_call_success(request_type): client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {} + request_init = {"parent": "spaces/sample1"} request = request_type(**request_init) # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = reaction.ListCustomEmojisResponse( + return_value = space_event.ListSpaceEventsResponse( next_page_token="next_page_token_value", ) @@ -27275,20 +32480,20 @@ def test_list_custom_emojis_rest_call_success(request_type): response_value.status_code = 200 # Convert return value to protobuf type - return_value = reaction.ListCustomEmojisResponse.pb(return_value) + return_value = space_event.ListSpaceEventsResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value.content = json_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_custom_emojis(request) + response = client.list_space_events(request) # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListCustomEmojisPager) + assert isinstance(response, pagers.ListSpaceEventsPager) assert response.next_page_token == "next_page_token_value" @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_custom_emojis_rest_interceptors(null_interceptor): +def test_list_space_events_rest_interceptors(null_interceptor): transport = transports.ChatServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -27301,21 +32506,21 @@ def test_list_custom_emojis_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.ChatServiceRestInterceptor, "post_list_custom_emojis" + transports.ChatServiceRestInterceptor, "post_list_space_events" ) as post, mock.patch.object( transports.ChatServiceRestInterceptor, - "post_list_custom_emojis_with_metadata", + "post_list_space_events_with_metadata", ) as post_with_metadata, mock.patch.object( - transports.ChatServiceRestInterceptor, "pre_list_custom_emojis" + transports.ChatServiceRestInterceptor, "pre_list_space_events" ) as pre, ): pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = reaction.ListCustomEmojisRequest.pb( - reaction.ListCustomEmojisRequest() + pb_message = space_event.ListSpaceEventsRequest.pb( + space_event.ListSpaceEventsRequest() ) transcode.return_value = { "method": "post", @@ -27327,21 +32532,24 @@ def test_list_custom_emojis_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 = reaction.ListCustomEmojisResponse.to_json( - reaction.ListCustomEmojisResponse() + return_value = space_event.ListSpaceEventsResponse.to_json( + space_event.ListSpaceEventsResponse() ) req.return_value.content = return_value - request = reaction.ListCustomEmojisRequest() + request = space_event.ListSpaceEventsRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = reaction.ListCustomEmojisResponse() - post_with_metadata.return_value = reaction.ListCustomEmojisResponse(), metadata + post.return_value = space_event.ListSpaceEventsResponse() + post_with_metadata.return_value = ( + space_event.ListSpaceEventsResponse(), + metadata, + ) - client.list_custom_emojis( + client.list_space_events( request, metadata=[ ("key", "val"), @@ -27354,14 +32562,14 @@ def test_list_custom_emojis_rest_interceptors(null_interceptor): post_with_metadata.assert_called_once() -def test_delete_custom_emoji_rest_bad_request( - request_type=reaction.DeleteCustomEmojiRequest, +def test_get_space_notification_setting_rest_bad_request( + request_type=space_notification_setting.GetSpaceNotificationSettingRequest, ): client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {"name": "customEmojis/sample1"} + request_init = {"name": "users/sample1/spaces/sample2/spaceNotificationSetting"} request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -27377,45 +32585,63 @@ def test_delete_custom_emoji_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_custom_emoji(request) + client.get_space_notification_setting(request) @pytest.mark.parametrize( "request_type", [ - reaction.DeleteCustomEmojiRequest, + space_notification_setting.GetSpaceNotificationSettingRequest, dict, ], ) -def test_delete_custom_emoji_rest_call_success(request_type): +def test_get_space_notification_setting_rest_call_success(request_type): client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {"name": "customEmojis/sample1"} + request_init = {"name": "users/sample1/spaces/sample2/spaceNotificationSetting"} request = request_type(**request_init) # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = None + return_value = space_notification_setting.SpaceNotificationSetting( + name="name_value", + notification_setting=space_notification_setting.SpaceNotificationSetting.NotificationSetting.ALL, + mute_setting=space_notification_setting.SpaceNotificationSetting.MuteSetting.UNMUTED, + ) # Wrap the value into a proper Response obj response_value = mock.Mock() response_value.status_code = 200 - json_return_value = "" + + # Convert return value to protobuf type + return_value = space_notification_setting.SpaceNotificationSetting.pb( + return_value + ) + json_return_value = json_format.MessageToJson(return_value) response_value.content = json_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_custom_emoji(request) + response = client.get_space_notification_setting(request) # Establish that the response is the type that we expect. - assert response is None + assert isinstance(response, space_notification_setting.SpaceNotificationSetting) + assert response.name == "name_value" + assert ( + response.notification_setting + == space_notification_setting.SpaceNotificationSetting.NotificationSetting.ALL + ) + assert ( + response.mute_setting + == space_notification_setting.SpaceNotificationSetting.MuteSetting.UNMUTED + ) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_delete_custom_emoji_rest_interceptors(null_interceptor): +def test_get_space_notification_setting_rest_interceptors(null_interceptor): transport = transports.ChatServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -27428,12 +32654,21 @@ def test_delete_custom_emoji_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.ChatServiceRestInterceptor, "pre_delete_custom_emoji" + transports.ChatServiceRestInterceptor, "post_get_space_notification_setting" + ) as post, + mock.patch.object( + transports.ChatServiceRestInterceptor, + "post_get_space_notification_setting_with_metadata", + ) as post_with_metadata, + mock.patch.object( + transports.ChatServiceRestInterceptor, "pre_get_space_notification_setting" ) as pre, ): pre.assert_not_called() - pb_message = reaction.DeleteCustomEmojiRequest.pb( - reaction.DeleteCustomEmojiRequest() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = space_notification_setting.GetSpaceNotificationSettingRequest.pb( + space_notification_setting.GetSpaceNotificationSettingRequest() ) transcode.return_value = { "method": "post", @@ -27445,15 +32680,24 @@ def test_delete_custom_emoji_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 = space_notification_setting.SpaceNotificationSetting.to_json( + space_notification_setting.SpaceNotificationSetting() + ) + req.return_value.content = return_value - request = reaction.DeleteCustomEmojiRequest() + request = space_notification_setting.GetSpaceNotificationSettingRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata + post.return_value = space_notification_setting.SpaceNotificationSetting() + post_with_metadata.return_value = ( + space_notification_setting.SpaceNotificationSetting(), + metadata, + ) - client.delete_custom_emoji( + client.get_space_notification_setting( request, metadata=[ ("key", "val"), @@ -27462,16 +32706,22 @@ def test_delete_custom_emoji_rest_interceptors(null_interceptor): ) pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() -def test_get_space_read_state_rest_bad_request( - request_type=space_read_state.GetSpaceReadStateRequest, +def test_update_space_notification_setting_rest_bad_request( + request_type=gc_space_notification_setting.UpdateSpaceNotificationSettingRequest, ): client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {"name": "users/sample1/spaces/sample2/spaceReadState"} + request_init = { + "space_notification_setting": { + "name": "users/sample1/spaces/sample2/spaceNotificationSetting" + } + } request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -27487,30 +32737,116 @@ def test_get_space_read_state_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_space_read_state(request) + client.update_space_notification_setting(request) @pytest.mark.parametrize( "request_type", [ - space_read_state.GetSpaceReadStateRequest, + gc_space_notification_setting.UpdateSpaceNotificationSettingRequest, dict, ], ) -def test_get_space_read_state_rest_call_success(request_type): +def test_update_space_notification_setting_rest_call_success(request_type): client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {"name": "users/sample1/spaces/sample2/spaceReadState"} + request_init = { + "space_notification_setting": { + "name": "users/sample1/spaces/sample2/spaceNotificationSetting" + } + } + request_init["space_notification_setting"] = { + "name": "users/sample1/spaces/sample2/spaceNotificationSetting", + "notification_setting": 1, + "mute_setting": 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 = ( + gc_space_notification_setting.UpdateSpaceNotificationSettingRequest.meta.fields[ + "space_notification_setting" + ] + ) + + 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[ + "space_notification_setting" + ].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["space_notification_setting"][field]) + ): + del request_init["space_notification_setting"][field][i][subfield] + else: + del request_init["space_notification_setting"][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 = space_read_state.SpaceReadState( + return_value = gc_space_notification_setting.SpaceNotificationSetting( name="name_value", + notification_setting=gc_space_notification_setting.SpaceNotificationSetting.NotificationSetting.ALL, + mute_setting=gc_space_notification_setting.SpaceNotificationSetting.MuteSetting.UNMUTED, ) # Wrap the value into a proper Response obj @@ -27518,20 +32854,30 @@ def test_get_space_read_state_rest_call_success(request_type): response_value.status_code = 200 # Convert return value to protobuf type - return_value = space_read_state.SpaceReadState.pb(return_value) + return_value = gc_space_notification_setting.SpaceNotificationSetting.pb( + return_value + ) json_return_value = json_format.MessageToJson(return_value) response_value.content = json_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_space_read_state(request) + response = client.update_space_notification_setting(request) # Establish that the response is the type that we expect. - assert isinstance(response, space_read_state.SpaceReadState) + assert isinstance(response, gc_space_notification_setting.SpaceNotificationSetting) assert response.name == "name_value" + assert ( + response.notification_setting + == gc_space_notification_setting.SpaceNotificationSetting.NotificationSetting.ALL + ) + assert ( + response.mute_setting + == gc_space_notification_setting.SpaceNotificationSetting.MuteSetting.UNMUTED + ) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_space_read_state_rest_interceptors(null_interceptor): +def test_update_space_notification_setting_rest_interceptors(null_interceptor): transport = transports.ChatServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -27544,21 +32890,25 @@ def test_get_space_read_state_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.ChatServiceRestInterceptor, "post_get_space_read_state" + transports.ChatServiceRestInterceptor, + "post_update_space_notification_setting", ) as post, mock.patch.object( transports.ChatServiceRestInterceptor, - "post_get_space_read_state_with_metadata", + "post_update_space_notification_setting_with_metadata", ) as post_with_metadata, mock.patch.object( - transports.ChatServiceRestInterceptor, "pre_get_space_read_state" + transports.ChatServiceRestInterceptor, + "pre_update_space_notification_setting", ) as pre, ): pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = space_read_state.GetSpaceReadStateRequest.pb( - space_read_state.GetSpaceReadStateRequest() + pb_message = ( + gc_space_notification_setting.UpdateSpaceNotificationSettingRequest.pb( + gc_space_notification_setting.UpdateSpaceNotificationSettingRequest() + ) ) transcode.return_value = { "method": "post", @@ -27570,21 +32920,24 @@ def test_get_space_read_state_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 = space_read_state.SpaceReadState.to_json( - space_read_state.SpaceReadState() + return_value = gc_space_notification_setting.SpaceNotificationSetting.to_json( + gc_space_notification_setting.SpaceNotificationSetting() ) req.return_value.content = return_value - request = space_read_state.GetSpaceReadStateRequest() + request = gc_space_notification_setting.UpdateSpaceNotificationSettingRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = space_read_state.SpaceReadState() - post_with_metadata.return_value = space_read_state.SpaceReadState(), metadata + post.return_value = gc_space_notification_setting.SpaceNotificationSetting() + post_with_metadata.return_value = ( + gc_space_notification_setting.SpaceNotificationSetting(), + metadata, + ) - client.get_space_read_state( + client.update_space_notification_setting( request, metadata=[ ("key", "val"), @@ -27597,16 +32950,12 @@ def test_get_space_read_state_rest_interceptors(null_interceptor): post_with_metadata.assert_called_once() -def test_update_space_read_state_rest_bad_request( - request_type=gc_space_read_state.UpdateSpaceReadStateRequest, -): +def test_create_section_rest_bad_request(request_type=gc_section.CreateSectionRequest): client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = { - "space_read_state": {"name": "users/sample1/spaces/sample2/spaceReadState"} - } + request_init = {"parent": "users/sample1"} request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -27622,37 +32971,35 @@ def test_update_space_read_state_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_space_read_state(request) + client.create_section(request) @pytest.mark.parametrize( "request_type", [ - gc_space_read_state.UpdateSpaceReadStateRequest, + gc_section.CreateSectionRequest, dict, ], ) -def test_update_space_read_state_rest_call_success(request_type): +def test_create_section_rest_call_success(request_type): client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = { - "space_read_state": {"name": "users/sample1/spaces/sample2/spaceReadState"} - } - request_init["space_read_state"] = { - "name": "users/sample1/spaces/sample2/spaceReadState", - "last_read_time": {"seconds": 751, "nanos": 543}, + request_init = {"parent": "users/sample1"} + request_init["section"] = { + "name": "name_value", + "display_name": "display_name_value", + "sort_order": 1091, + "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 = gc_space_read_state.UpdateSpaceReadStateRequest.meta.fields[ - "space_read_state" - ] + test_field = gc_section.CreateSectionRequest.meta.fields["section"] def get_message_fields(field): # Given a field which is a message (composite type), return a list with @@ -27680,7 +33027,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["space_read_state"].items(): # pragma: NO COVER + for field, value in request_init["section"].items(): # pragma: NO COVER result = None is_repeated = False # For repeated fields @@ -27710,17 +33057,20 @@ def get_message_fields(field): subfield = subfield_to_delete.get("subfield") if subfield: if field_repeated: - for i in range(0, len(request_init["space_read_state"][field])): - del request_init["space_read_state"][field][i][subfield] + for i in range(0, len(request_init["section"][field])): + del request_init["section"][field][i][subfield] else: - del request_init["space_read_state"][field][subfield] + del request_init["section"][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 = gc_space_read_state.SpaceReadState( + return_value = gc_section.Section( name="name_value", + display_name="display_name_value", + sort_order=1091, + type_=gc_section.Section.SectionType.CUSTOM_SECTION, ) # Wrap the value into a proper Response obj @@ -27728,20 +33078,23 @@ def get_message_fields(field): response_value.status_code = 200 # Convert return value to protobuf type - return_value = gc_space_read_state.SpaceReadState.pb(return_value) + return_value = gc_section.Section.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value.content = json_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_space_read_state(request) + response = client.create_section(request) # Establish that the response is the type that we expect. - assert isinstance(response, gc_space_read_state.SpaceReadState) + assert isinstance(response, gc_section.Section) assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.sort_order == 1091 + assert response.type_ == gc_section.Section.SectionType.CUSTOM_SECTION @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_update_space_read_state_rest_interceptors(null_interceptor): +def test_create_section_rest_interceptors(null_interceptor): transport = transports.ChatServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -27754,21 +33107,20 @@ def test_update_space_read_state_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.ChatServiceRestInterceptor, "post_update_space_read_state" + transports.ChatServiceRestInterceptor, "post_create_section" ) as post, mock.patch.object( - transports.ChatServiceRestInterceptor, - "post_update_space_read_state_with_metadata", + transports.ChatServiceRestInterceptor, "post_create_section_with_metadata" ) as post_with_metadata, mock.patch.object( - transports.ChatServiceRestInterceptor, "pre_update_space_read_state" + transports.ChatServiceRestInterceptor, "pre_create_section" ) as pre, ): pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = gc_space_read_state.UpdateSpaceReadStateRequest.pb( - gc_space_read_state.UpdateSpaceReadStateRequest() + pb_message = gc_section.CreateSectionRequest.pb( + gc_section.CreateSectionRequest() ) transcode.return_value = { "method": "post", @@ -27780,21 +33132,19 @@ def test_update_space_read_state_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 = gc_space_read_state.SpaceReadState.to_json( - gc_space_read_state.SpaceReadState() - ) + return_value = gc_section.Section.to_json(gc_section.Section()) req.return_value.content = return_value - request = gc_space_read_state.UpdateSpaceReadStateRequest() + request = gc_section.CreateSectionRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = gc_space_read_state.SpaceReadState() - post_with_metadata.return_value = gc_space_read_state.SpaceReadState(), metadata + post.return_value = gc_section.Section() + post_with_metadata.return_value = gc_section.Section(), metadata - client.update_space_read_state( + client.create_section( request, metadata=[ ("key", "val"), @@ -27807,57 +33157,233 @@ def test_update_space_read_state_rest_interceptors(null_interceptor): post_with_metadata.assert_called_once() -def test_get_thread_read_state_rest_bad_request( - request_type=thread_read_state.GetThreadReadStateRequest, -): +def test_delete_section_rest_bad_request(request_type=section.DeleteSectionRequest): client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = { - "name": "users/sample1/spaces/sample2/threads/sample3/threadReadState" - } + request_init = {"name": "users/sample1/sections/sample2"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.delete_section(request) + + +@pytest.mark.parametrize( + "request_type", + [ + section.DeleteSectionRequest, + dict, + ], +) +def test_delete_section_rest_call_success(request_type): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"name": "users/sample1/sections/sample2"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = None + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = "" + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.delete_section(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_section_rest_interceptors(null_interceptor): + transport = transports.ChatServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.ChatServiceRestInterceptor(), + ) + client = ChatServiceClient(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.ChatServiceRestInterceptor, "pre_delete_section" + ) as pre, + ): + pre.assert_not_called() + pb_message = section.DeleteSectionRequest.pb(section.DeleteSectionRequest()) + 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 = section.DeleteSectionRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + + client.delete_section( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + + +def test_update_section_rest_bad_request(request_type=gc_section.UpdateSectionRequest): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"section": {"name": "users/sample1/sections/sample2"}} request = request_type(**request_init) - # Mock the http request call within the method and fake a BadRequest error. - with ( - mock.patch.object(Session, "request") as req, - pytest.raises(core_exceptions.BadRequest), - ): - # Wrap the value into a proper Response obj - response_value = mock.Mock() - json_return_value = "" - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = mock.Mock() - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.get_thread_read_state(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 = 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_section(request) + + +@pytest.mark.parametrize( + "request_type", + [ + gc_section.UpdateSectionRequest, + dict, + ], +) +def test_update_section_rest_call_success(request_type): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"section": {"name": "users/sample1/sections/sample2"}} + request_init["section"] = { + "name": "users/sample1/sections/sample2", + "display_name": "display_name_value", + "sort_order": 1091, + "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 = gc_section.UpdateSectionRequest.meta.fields["section"] + + 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["section"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value -@pytest.mark.parametrize( - "request_type", - [ - thread_read_state.GetThreadReadStateRequest, - dict, - ], -) -def test_get_thread_read_state_rest_call_success(request_type): - client = ChatServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + { + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + } + ) - # send a request that will satisfy transcoding - request_init = { - "name": "users/sample1/spaces/sample2/threads/sample3/threadReadState" - } + # 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["section"][field])): + del request_init["section"][field][i][subfield] + else: + del request_init["section"][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 = thread_read_state.ThreadReadState( + return_value = gc_section.Section( name="name_value", + display_name="display_name_value", + sort_order=1091, + type_=gc_section.Section.SectionType.CUSTOM_SECTION, ) # Wrap the value into a proper Response obj @@ -27865,20 +33391,23 @@ def test_get_thread_read_state_rest_call_success(request_type): response_value.status_code = 200 # Convert return value to protobuf type - return_value = thread_read_state.ThreadReadState.pb(return_value) + return_value = gc_section.Section.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value.content = json_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_thread_read_state(request) + response = client.update_section(request) # Establish that the response is the type that we expect. - assert isinstance(response, thread_read_state.ThreadReadState) + assert isinstance(response, gc_section.Section) assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.sort_order == 1091 + assert response.type_ == gc_section.Section.SectionType.CUSTOM_SECTION @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_thread_read_state_rest_interceptors(null_interceptor): +def test_update_section_rest_interceptors(null_interceptor): transport = transports.ChatServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -27891,21 +33420,20 @@ def test_get_thread_read_state_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.ChatServiceRestInterceptor, "post_get_thread_read_state" + transports.ChatServiceRestInterceptor, "post_update_section" ) as post, mock.patch.object( - transports.ChatServiceRestInterceptor, - "post_get_thread_read_state_with_metadata", + transports.ChatServiceRestInterceptor, "post_update_section_with_metadata" ) as post_with_metadata, mock.patch.object( - transports.ChatServiceRestInterceptor, "pre_get_thread_read_state" + transports.ChatServiceRestInterceptor, "pre_update_section" ) as pre, ): pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = thread_read_state.GetThreadReadStateRequest.pb( - thread_read_state.GetThreadReadStateRequest() + pb_message = gc_section.UpdateSectionRequest.pb( + gc_section.UpdateSectionRequest() ) transcode.return_value = { "method": "post", @@ -27917,21 +33445,19 @@ def test_get_thread_read_state_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 = thread_read_state.ThreadReadState.to_json( - thread_read_state.ThreadReadState() - ) + return_value = gc_section.Section.to_json(gc_section.Section()) req.return_value.content = return_value - request = thread_read_state.GetThreadReadStateRequest() + request = gc_section.UpdateSectionRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = thread_read_state.ThreadReadState() - post_with_metadata.return_value = thread_read_state.ThreadReadState(), metadata + post.return_value = gc_section.Section() + post_with_metadata.return_value = gc_section.Section(), metadata - client.get_thread_read_state( + client.update_section( request, metadata=[ ("key", "val"), @@ -27944,14 +33470,12 @@ def test_get_thread_read_state_rest_interceptors(null_interceptor): post_with_metadata.assert_called_once() -def test_get_space_event_rest_bad_request( - request_type=space_event.GetSpaceEventRequest, -): +def test_list_sections_rest_bad_request(request_type=section.ListSectionsRequest): client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {"name": "spaces/sample1/spaceEvents/sample2"} + request_init = {"parent": "users/sample1"} request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -27967,31 +33491,30 @@ def test_get_space_event_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_space_event(request) + client.list_sections(request) @pytest.mark.parametrize( "request_type", [ - space_event.GetSpaceEventRequest, + section.ListSectionsRequest, dict, ], ) -def test_get_space_event_rest_call_success(request_type): +def test_list_sections_rest_call_success(request_type): client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {"name": "spaces/sample1/spaceEvents/sample2"} + request_init = {"parent": "users/sample1"} request = request_type(**request_init) # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = space_event.SpaceEvent( - name="name_value", - event_type="event_type_value", + return_value = section.ListSectionsResponse( + next_page_token="next_page_token_value", ) # Wrap the value into a proper Response obj @@ -27999,21 +33522,20 @@ def test_get_space_event_rest_call_success(request_type): response_value.status_code = 200 # Convert return value to protobuf type - return_value = space_event.SpaceEvent.pb(return_value) + return_value = section.ListSectionsResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value.content = json_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_space_event(request) + response = client.list_sections(request) # Establish that the response is the type that we expect. - assert isinstance(response, space_event.SpaceEvent) - assert response.name == "name_value" - assert response.event_type == "event_type_value" + assert isinstance(response, pagers.ListSectionsPager) + assert response.next_page_token == "next_page_token_value" @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_space_event_rest_interceptors(null_interceptor): +def test_list_sections_rest_interceptors(null_interceptor): transport = transports.ChatServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -28026,21 +33548,19 @@ def test_get_space_event_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.ChatServiceRestInterceptor, "post_get_space_event" + transports.ChatServiceRestInterceptor, "post_list_sections" ) as post, mock.patch.object( - transports.ChatServiceRestInterceptor, "post_get_space_event_with_metadata" + transports.ChatServiceRestInterceptor, "post_list_sections_with_metadata" ) as post_with_metadata, mock.patch.object( - transports.ChatServiceRestInterceptor, "pre_get_space_event" + transports.ChatServiceRestInterceptor, "pre_list_sections" ) as pre, ): pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = space_event.GetSpaceEventRequest.pb( - space_event.GetSpaceEventRequest() - ) + pb_message = section.ListSectionsRequest.pb(section.ListSectionsRequest()) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -28051,19 +33571,21 @@ def test_get_space_event_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 = space_event.SpaceEvent.to_json(space_event.SpaceEvent()) + return_value = section.ListSectionsResponse.to_json( + section.ListSectionsResponse() + ) req.return_value.content = return_value - request = space_event.GetSpaceEventRequest() + request = section.ListSectionsRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = space_event.SpaceEvent() - post_with_metadata.return_value = space_event.SpaceEvent(), metadata + post.return_value = section.ListSectionsResponse() + post_with_metadata.return_value = section.ListSectionsResponse(), metadata - client.get_space_event( + client.list_sections( request, metadata=[ ("key", "val"), @@ -28076,14 +33598,12 @@ def test_get_space_event_rest_interceptors(null_interceptor): post_with_metadata.assert_called_once() -def test_list_space_events_rest_bad_request( - request_type=space_event.ListSpaceEventsRequest, -): +def test_position_section_rest_bad_request(request_type=section.PositionSectionRequest): client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {"parent": "spaces/sample1"} + request_init = {"name": "users/sample1/sections/sample2"} request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -28099,51 +33619,48 @@ def test_list_space_events_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_space_events(request) + client.position_section(request) @pytest.mark.parametrize( "request_type", [ - space_event.ListSpaceEventsRequest, + section.PositionSectionRequest, dict, ], ) -def test_list_space_events_rest_call_success(request_type): +def test_position_section_rest_call_success(request_type): client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {"parent": "spaces/sample1"} + request_init = {"name": "users/sample1/sections/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 = space_event.ListSpaceEventsResponse( - next_page_token="next_page_token_value", - ) + return_value = section.PositionSectionResponse() # 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 = space_event.ListSpaceEventsResponse.pb(return_value) + return_value = section.PositionSectionResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value.content = json_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_space_events(request) + response = client.position_section(request) # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListSpaceEventsPager) - assert response.next_page_token == "next_page_token_value" + assert isinstance(response, section.PositionSectionResponse) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_space_events_rest_interceptors(null_interceptor): +def test_position_section_rest_interceptors(null_interceptor): transport = transports.ChatServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -28156,22 +33673,19 @@ def test_list_space_events_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.ChatServiceRestInterceptor, "post_list_space_events" + transports.ChatServiceRestInterceptor, "post_position_section" ) as post, mock.patch.object( - transports.ChatServiceRestInterceptor, - "post_list_space_events_with_metadata", + transports.ChatServiceRestInterceptor, "post_position_section_with_metadata" ) as post_with_metadata, mock.patch.object( - transports.ChatServiceRestInterceptor, "pre_list_space_events" + transports.ChatServiceRestInterceptor, "pre_position_section" ) as pre, ): pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = space_event.ListSpaceEventsRequest.pb( - space_event.ListSpaceEventsRequest() - ) + pb_message = section.PositionSectionRequest.pb(section.PositionSectionRequest()) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -28182,24 +33696,21 @@ def test_list_space_events_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 = space_event.ListSpaceEventsResponse.to_json( - space_event.ListSpaceEventsResponse() + return_value = section.PositionSectionResponse.to_json( + section.PositionSectionResponse() ) req.return_value.content = return_value - request = space_event.ListSpaceEventsRequest() + request = section.PositionSectionRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = space_event.ListSpaceEventsResponse() - post_with_metadata.return_value = ( - space_event.ListSpaceEventsResponse(), - metadata, - ) + post.return_value = section.PositionSectionResponse() + post_with_metadata.return_value = section.PositionSectionResponse(), metadata - client.list_space_events( + client.position_section( request, metadata=[ ("key", "val"), @@ -28212,14 +33723,14 @@ def test_list_space_events_rest_interceptors(null_interceptor): post_with_metadata.assert_called_once() -def test_get_space_notification_setting_rest_bad_request( - request_type=space_notification_setting.GetSpaceNotificationSettingRequest, +def test_list_section_items_rest_bad_request( + request_type=section.ListSectionItemsRequest, ): client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {"name": "users/sample1/spaces/sample2/spaceNotificationSetting"} + request_init = {"parent": "users/sample1/sections/sample2"} request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -28235,32 +33746,30 @@ def test_get_space_notification_setting_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_space_notification_setting(request) + client.list_section_items(request) @pytest.mark.parametrize( "request_type", [ - space_notification_setting.GetSpaceNotificationSettingRequest, + section.ListSectionItemsRequest, dict, ], ) -def test_get_space_notification_setting_rest_call_success(request_type): +def test_list_section_items_rest_call_success(request_type): client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {"name": "users/sample1/spaces/sample2/spaceNotificationSetting"} + request_init = {"parent": "users/sample1/sections/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 = space_notification_setting.SpaceNotificationSetting( - name="name_value", - notification_setting=space_notification_setting.SpaceNotificationSetting.NotificationSetting.ALL, - mute_setting=space_notification_setting.SpaceNotificationSetting.MuteSetting.UNMUTED, + return_value = section.ListSectionItemsResponse( + next_page_token="next_page_token_value", ) # Wrap the value into a proper Response obj @@ -28268,30 +33777,20 @@ def test_get_space_notification_setting_rest_call_success(request_type): response_value.status_code = 200 # Convert return value to protobuf type - return_value = space_notification_setting.SpaceNotificationSetting.pb( - return_value - ) + return_value = section.ListSectionItemsResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value.content = json_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_space_notification_setting(request) + response = client.list_section_items(request) # Establish that the response is the type that we expect. - assert isinstance(response, space_notification_setting.SpaceNotificationSetting) - assert response.name == "name_value" - assert ( - response.notification_setting - == space_notification_setting.SpaceNotificationSetting.NotificationSetting.ALL - ) - assert ( - response.mute_setting - == space_notification_setting.SpaceNotificationSetting.MuteSetting.UNMUTED - ) + assert isinstance(response, pagers.ListSectionItemsPager) + assert response.next_page_token == "next_page_token_value" @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_space_notification_setting_rest_interceptors(null_interceptor): +def test_list_section_items_rest_interceptors(null_interceptor): transport = transports.ChatServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -28304,21 +33803,21 @@ def test_get_space_notification_setting_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.ChatServiceRestInterceptor, "post_get_space_notification_setting" + transports.ChatServiceRestInterceptor, "post_list_section_items" ) as post, mock.patch.object( transports.ChatServiceRestInterceptor, - "post_get_space_notification_setting_with_metadata", + "post_list_section_items_with_metadata", ) as post_with_metadata, mock.patch.object( - transports.ChatServiceRestInterceptor, "pre_get_space_notification_setting" + transports.ChatServiceRestInterceptor, "pre_list_section_items" ) as pre, ): pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = space_notification_setting.GetSpaceNotificationSettingRequest.pb( - space_notification_setting.GetSpaceNotificationSettingRequest() + pb_message = section.ListSectionItemsRequest.pb( + section.ListSectionItemsRequest() ) transcode.return_value = { "method": "post", @@ -28330,24 +33829,21 @@ def test_get_space_notification_setting_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 = space_notification_setting.SpaceNotificationSetting.to_json( - space_notification_setting.SpaceNotificationSetting() + return_value = section.ListSectionItemsResponse.to_json( + section.ListSectionItemsResponse() ) req.return_value.content = return_value - request = space_notification_setting.GetSpaceNotificationSettingRequest() + request = section.ListSectionItemsRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = space_notification_setting.SpaceNotificationSetting() - post_with_metadata.return_value = ( - space_notification_setting.SpaceNotificationSetting(), - metadata, - ) + post.return_value = section.ListSectionItemsResponse() + post_with_metadata.return_value = section.ListSectionItemsResponse(), metadata - client.get_space_notification_setting( + client.list_section_items( request, metadata=[ ("key", "val"), @@ -28360,18 +33856,14 @@ def test_get_space_notification_setting_rest_interceptors(null_interceptor): post_with_metadata.assert_called_once() -def test_update_space_notification_setting_rest_bad_request( - request_type=gc_space_notification_setting.UpdateSpaceNotificationSettingRequest, +def test_move_section_item_rest_bad_request( + request_type=section.MoveSectionItemRequest, ): client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = { - "space_notification_setting": { - "name": "users/sample1/spaces/sample2/spaceNotificationSetting" - } - } + request_init = {"name": "users/sample1/sections/sample2/items/sample3"} request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -28386,148 +33878,49 @@ def test_update_space_notification_setting_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_space_notification_setting(request) - - -@pytest.mark.parametrize( - "request_type", - [ - gc_space_notification_setting.UpdateSpaceNotificationSettingRequest, - dict, - ], -) -def test_update_space_notification_setting_rest_call_success(request_type): - client = ChatServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = { - "space_notification_setting": { - "name": "users/sample1/spaces/sample2/spaceNotificationSetting" - } - } - request_init["space_notification_setting"] = { - "name": "users/sample1/spaces/sample2/spaceNotificationSetting", - "notification_setting": 1, - "mute_setting": 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 = ( - gc_space_notification_setting.UpdateSpaceNotificationSettingRequest.meta.fields[ - "space_notification_setting" - ] - ) - - 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 = [] + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.move_section_item(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[ - "space_notification_setting" - ].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", + [ + section.MoveSectionItemRequest, + dict, + ], +) +def test_move_section_item_rest_call_success(request_type): + client = ChatServiceClient( + 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["space_notification_setting"][field]) - ): - del request_init["space_notification_setting"][field][i][subfield] - else: - del request_init["space_notification_setting"][field][subfield] + # send a request that will satisfy transcoding + request_init = {"name": "users/sample1/sections/sample2/items/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 = gc_space_notification_setting.SpaceNotificationSetting( - name="name_value", - notification_setting=gc_space_notification_setting.SpaceNotificationSetting.NotificationSetting.ALL, - mute_setting=gc_space_notification_setting.SpaceNotificationSetting.MuteSetting.UNMUTED, - ) + return_value = section.MoveSectionItemResponse() # 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 = gc_space_notification_setting.SpaceNotificationSetting.pb( - return_value - ) + return_value = section.MoveSectionItemResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value.content = json_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_space_notification_setting(request) + response = client.move_section_item(request) # Establish that the response is the type that we expect. - assert isinstance(response, gc_space_notification_setting.SpaceNotificationSetting) - assert response.name == "name_value" - assert ( - response.notification_setting - == gc_space_notification_setting.SpaceNotificationSetting.NotificationSetting.ALL - ) - assert ( - response.mute_setting - == gc_space_notification_setting.SpaceNotificationSetting.MuteSetting.UNMUTED - ) + assert isinstance(response, section.MoveSectionItemResponse) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_update_space_notification_setting_rest_interceptors(null_interceptor): +def test_move_section_item_rest_interceptors(null_interceptor): transport = transports.ChatServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -28540,26 +33933,20 @@ def test_update_space_notification_setting_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.ChatServiceRestInterceptor, - "post_update_space_notification_setting", + transports.ChatServiceRestInterceptor, "post_move_section_item" ) as post, mock.patch.object( transports.ChatServiceRestInterceptor, - "post_update_space_notification_setting_with_metadata", + "post_move_section_item_with_metadata", ) as post_with_metadata, mock.patch.object( - transports.ChatServiceRestInterceptor, - "pre_update_space_notification_setting", + transports.ChatServiceRestInterceptor, "pre_move_section_item" ) as pre, ): pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = ( - gc_space_notification_setting.UpdateSpaceNotificationSettingRequest.pb( - gc_space_notification_setting.UpdateSpaceNotificationSettingRequest() - ) - ) + pb_message = section.MoveSectionItemRequest.pb(section.MoveSectionItemRequest()) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -28570,24 +33957,21 @@ def test_update_space_notification_setting_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 = gc_space_notification_setting.SpaceNotificationSetting.to_json( - gc_space_notification_setting.SpaceNotificationSetting() + return_value = section.MoveSectionItemResponse.to_json( + section.MoveSectionItemResponse() ) req.return_value.content = return_value - request = gc_space_notification_setting.UpdateSpaceNotificationSettingRequest() + request = section.MoveSectionItemRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = gc_space_notification_setting.SpaceNotificationSetting() - post_with_metadata.return_value = ( - gc_space_notification_setting.SpaceNotificationSetting(), - metadata, - ) + post.return_value = section.MoveSectionItemResponse() + post_with_metadata.return_value = section.MoveSectionItemResponse(), metadata - client.update_space_notification_setting( + client.move_section_item( request, metadata=[ ("key", "val"), @@ -29339,6 +34723,150 @@ def test_update_space_notification_setting_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_section_empty_call_rest(): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.create_section), "__call__") as call: + client.create_section(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = gc_section.CreateSectionRequest() + + assert args[0] == request_msg + + +# This 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_section_empty_call_rest(): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.delete_section), "__call__") as call: + client.delete_section(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = section.DeleteSectionRequest() + + assert args[0] == request_msg + + +# This 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_section_empty_call_rest(): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.update_section), "__call__") as call: + client.update_section(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = gc_section.UpdateSectionRequest() + + assert args[0] == request_msg + + +# This 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_sections_empty_call_rest(): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.list_sections), "__call__") as call: + client.list_sections(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = section.ListSectionsRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_position_section_empty_call_rest(): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.position_section), "__call__") as call: + client.position_section(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = section.PositionSectionRequest() + + assert args[0] == request_msg + + +# This 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_section_items_empty_call_rest(): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_section_items), "__call__" + ) as call: + client.list_section_items(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = section.ListSectionItemsRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_move_section_item_empty_call_rest(): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.move_section_item), "__call__" + ) as call: + client.move_section_item(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = section.MoveSectionItemRequest() + + assert args[0] == request_msg + + def test_transport_grpc_default(): # A client should use the gRPC transport by default. client = ChatServiceClient( @@ -29407,6 +34935,13 @@ def test_chat_service_base_transport(): "list_space_events", "get_space_notification_setting", "update_space_notification_setting", + "create_section", + "delete_section", + "update_section", + "list_sections", + "position_section", + "list_section_items", + "move_section_item", ) for method in methods: with pytest.raises(NotImplementedError): @@ -29451,9 +34986,11 @@ def test_chat_service_base_transport_with_credentials_file(): "https://www.googleapis.com/auth/chat.admin.spaces.readonly", "https://www.googleapis.com/auth/chat.app.delete", "https://www.googleapis.com/auth/chat.app.memberships", + "https://www.googleapis.com/auth/chat.app.memberships.readonly", "https://www.googleapis.com/auth/chat.app.messages.readonly", "https://www.googleapis.com/auth/chat.app.spaces", "https://www.googleapis.com/auth/chat.app.spaces.create", + "https://www.googleapis.com/auth/chat.app.spaces.readonly", "https://www.googleapis.com/auth/chat.bot", "https://www.googleapis.com/auth/chat.customemojis", "https://www.googleapis.com/auth/chat.customemojis.readonly", @@ -29473,6 +35010,8 @@ def test_chat_service_base_transport_with_credentials_file(): "https://www.googleapis.com/auth/chat.spaces.readonly", "https://www.googleapis.com/auth/chat.users.readstate", "https://www.googleapis.com/auth/chat.users.readstate.readonly", + "https://www.googleapis.com/auth/chat.users.sections", + "https://www.googleapis.com/auth/chat.users.sections.readonly", "https://www.googleapis.com/auth/chat.users.spacesettings", ), quota_project_id="octopus", @@ -29508,9 +35047,11 @@ def test_chat_service_auth_adc(): "https://www.googleapis.com/auth/chat.admin.spaces.readonly", "https://www.googleapis.com/auth/chat.app.delete", "https://www.googleapis.com/auth/chat.app.memberships", + "https://www.googleapis.com/auth/chat.app.memberships.readonly", "https://www.googleapis.com/auth/chat.app.messages.readonly", "https://www.googleapis.com/auth/chat.app.spaces", "https://www.googleapis.com/auth/chat.app.spaces.create", + "https://www.googleapis.com/auth/chat.app.spaces.readonly", "https://www.googleapis.com/auth/chat.bot", "https://www.googleapis.com/auth/chat.customemojis", "https://www.googleapis.com/auth/chat.customemojis.readonly", @@ -29530,6 +35071,8 @@ def test_chat_service_auth_adc(): "https://www.googleapis.com/auth/chat.spaces.readonly", "https://www.googleapis.com/auth/chat.users.readstate", "https://www.googleapis.com/auth/chat.users.readstate.readonly", + "https://www.googleapis.com/auth/chat.users.sections", + "https://www.googleapis.com/auth/chat.users.sections.readonly", "https://www.googleapis.com/auth/chat.users.spacesettings", ), quota_project_id=None, @@ -29559,9 +35102,11 @@ def test_chat_service_transport_auth_adc(transport_class): "https://www.googleapis.com/auth/chat.admin.spaces.readonly", "https://www.googleapis.com/auth/chat.app.delete", "https://www.googleapis.com/auth/chat.app.memberships", + "https://www.googleapis.com/auth/chat.app.memberships.readonly", "https://www.googleapis.com/auth/chat.app.messages.readonly", "https://www.googleapis.com/auth/chat.app.spaces", "https://www.googleapis.com/auth/chat.app.spaces.create", + "https://www.googleapis.com/auth/chat.app.spaces.readonly", "https://www.googleapis.com/auth/chat.bot", "https://www.googleapis.com/auth/chat.customemojis", "https://www.googleapis.com/auth/chat.customemojis.readonly", @@ -29581,6 +35126,8 @@ def test_chat_service_transport_auth_adc(transport_class): "https://www.googleapis.com/auth/chat.spaces.readonly", "https://www.googleapis.com/auth/chat.users.readstate", "https://www.googleapis.com/auth/chat.users.readstate.readonly", + "https://www.googleapis.com/auth/chat.users.sections", + "https://www.googleapis.com/auth/chat.users.sections.readonly", "https://www.googleapis.com/auth/chat.users.spacesettings", ), quota_project_id="octopus", @@ -29643,9 +35190,11 @@ def test_chat_service_transport_create_channel(transport_class, grpc_helpers): "https://www.googleapis.com/auth/chat.admin.spaces.readonly", "https://www.googleapis.com/auth/chat.app.delete", "https://www.googleapis.com/auth/chat.app.memberships", + "https://www.googleapis.com/auth/chat.app.memberships.readonly", "https://www.googleapis.com/auth/chat.app.messages.readonly", "https://www.googleapis.com/auth/chat.app.spaces", "https://www.googleapis.com/auth/chat.app.spaces.create", + "https://www.googleapis.com/auth/chat.app.spaces.readonly", "https://www.googleapis.com/auth/chat.bot", "https://www.googleapis.com/auth/chat.customemojis", "https://www.googleapis.com/auth/chat.customemojis.readonly", @@ -29665,6 +35214,8 @@ def test_chat_service_transport_create_channel(transport_class, grpc_helpers): "https://www.googleapis.com/auth/chat.spaces.readonly", "https://www.googleapis.com/auth/chat.users.readstate", "https://www.googleapis.com/auth/chat.users.readstate.readonly", + "https://www.googleapis.com/auth/chat.users.sections", + "https://www.googleapis.com/auth/chat.users.sections.readonly", "https://www.googleapis.com/auth/chat.users.spacesettings", ), scopes=["1", "2"], @@ -29896,6 +35447,27 @@ def test_chat_service_client_transport_session_collision(transport_name): session1 = client1.transport.update_space_notification_setting._session session2 = client2.transport.update_space_notification_setting._session assert session1 != session2 + session1 = client1.transport.create_section._session + session2 = client2.transport.create_section._session + assert session1 != session2 + session1 = client1.transport.delete_section._session + session2 = client2.transport.delete_section._session + assert session1 != session2 + session1 = client1.transport.update_section._session + session2 = client2.transport.update_section._session + assert session1 != session2 + session1 = client1.transport.list_sections._session + session2 = client2.transport.list_sections._session + assert session1 != session2 + session1 = client1.transport.position_section._session + session2 = client2.transport.position_section._session + assert session1 != session2 + session1 = client1.transport.list_section_items._session + session2 = client2.transport.list_section_items._session + assert session1 != session2 + session1 = client1.transport.move_section_item._session + session2 = client2.transport.move_section_item._session + assert session1 != session2 def test_chat_service_grpc_transport_channel(): @@ -30163,8 +35735,57 @@ def test_parse_reaction_path(): assert expected == actual +def test_section_path(): + user = "oyster" + section = "nudibranch" + expected = "users/{user}/sections/{section}".format( + user=user, + section=section, + ) + actual = ChatServiceClient.section_path(user, section) + assert expected == actual + + +def test_parse_section_path(): + expected = { + "user": "cuttlefish", + "section": "mussel", + } + path = ChatServiceClient.section_path(**expected) + + # Check that the path construction is reversible. + actual = ChatServiceClient.parse_section_path(path) + assert expected == actual + + +def test_section_item_path(): + user = "winkle" + section = "nautilus" + item = "scallop" + expected = "users/{user}/sections/{section}/items/{item}".format( + user=user, + section=section, + item=item, + ) + actual = ChatServiceClient.section_item_path(user, section, item) + assert expected == actual + + +def test_parse_section_item_path(): + expected = { + "user": "abalone", + "section": "squid", + "item": "clam", + } + path = ChatServiceClient.section_item_path(**expected) + + # Check that the path construction is reversible. + actual = ChatServiceClient.parse_section_item_path(path) + assert expected == actual + + def test_space_path(): - space = "oyster" + space = "whelk" expected = "spaces/{space}".format( space=space, ) @@ -30174,7 +35795,7 @@ def test_space_path(): def test_parse_space_path(): expected = { - "space": "nudibranch", + "space": "octopus", } path = ChatServiceClient.space_path(**expected) @@ -30184,8 +35805,8 @@ def test_parse_space_path(): def test_space_event_path(): - space = "cuttlefish" - space_event = "mussel" + space = "oyster" + space_event = "nudibranch" expected = "spaces/{space}/spaceEvents/{space_event}".format( space=space, space_event=space_event, @@ -30196,8 +35817,8 @@ def test_space_event_path(): def test_parse_space_event_path(): expected = { - "space": "winkle", - "space_event": "nautilus", + "space": "cuttlefish", + "space_event": "mussel", } path = ChatServiceClient.space_event_path(**expected) @@ -30207,8 +35828,8 @@ def test_parse_space_event_path(): def test_space_notification_setting_path(): - user = "scallop" - space = "abalone" + user = "winkle" + space = "nautilus" expected = "users/{user}/spaces/{space}/spaceNotificationSetting".format( user=user, space=space, @@ -30219,8 +35840,8 @@ def test_space_notification_setting_path(): def test_parse_space_notification_setting_path(): expected = { - "user": "squid", - "space": "clam", + "user": "scallop", + "space": "abalone", } path = ChatServiceClient.space_notification_setting_path(**expected) @@ -30230,8 +35851,8 @@ def test_parse_space_notification_setting_path(): def test_space_read_state_path(): - user = "whelk" - space = "octopus" + user = "squid" + space = "clam" expected = "users/{user}/spaces/{space}/spaceReadState".format( user=user, space=space, @@ -30242,8 +35863,8 @@ def test_space_read_state_path(): def test_parse_space_read_state_path(): expected = { - "user": "oyster", - "space": "nudibranch", + "user": "whelk", + "space": "octopus", } path = ChatServiceClient.space_read_state_path(**expected) @@ -30253,8 +35874,8 @@ def test_parse_space_read_state_path(): def test_thread_path(): - space = "cuttlefish" - thread = "mussel" + space = "oyster" + thread = "nudibranch" expected = "spaces/{space}/threads/{thread}".format( space=space, thread=thread, @@ -30265,8 +35886,8 @@ def test_thread_path(): def test_parse_thread_path(): expected = { - "space": "winkle", - "thread": "nautilus", + "space": "cuttlefish", + "thread": "mussel", } path = ChatServiceClient.thread_path(**expected) @@ -30276,9 +35897,9 @@ def test_parse_thread_path(): def test_thread_read_state_path(): - user = "scallop" - space = "abalone" - thread = "squid" + user = "winkle" + space = "nautilus" + thread = "scallop" expected = "users/{user}/spaces/{space}/threads/{thread}/threadReadState".format( user=user, space=space, @@ -30290,9 +35911,9 @@ def test_thread_read_state_path(): def test_parse_thread_read_state_path(): expected = { - "user": "clam", - "space": "whelk", - "thread": "octopus", + "user": "abalone", + "space": "squid", + "thread": "clam", } path = ChatServiceClient.thread_read_state_path(**expected) @@ -30301,6 +35922,26 @@ def test_parse_thread_read_state_path(): assert expected == actual +def test_user_path(): + user = "whelk" + expected = "users/{user}".format( + user=user, + ) + actual = ChatServiceClient.user_path(user) + assert expected == actual + + +def test_parse_user_path(): + expected = { + "user": "octopus", + } + path = ChatServiceClient.user_path(**expected) + + # Check that the path construction is reversible. + actual = ChatServiceClient.parse_user_path(path) + assert expected == actual + + def test_common_billing_account_path(): billing_account = "oyster" expected = "billingAccounts/{billing_account}".format( diff --git a/packages/google-cloud-dlp/google/cloud/dlp/__init__.py b/packages/google-cloud-dlp/google/cloud/dlp/__init__.py index 4fa193fcb08c..9317e8861508 100644 --- a/packages/google-cloud-dlp/google/cloud/dlp/__init__.py +++ b/packages/google-cloud-dlp/google/cloud/dlp/__init__.py @@ -63,6 +63,7 @@ Container, ContentItem, ContentLocation, + ContentMetadata, ContentOption, CreateConnectionRequest, CreateDeidentifyTemplateRequest, @@ -193,6 +194,7 @@ InspectTemplate, JobTrigger, KeyValueMetadataLabel, + KeyValueMetadataProperty, KmsWrappedCryptoKey, LargeCustomDictionaryConfig, LargeCustomDictionaryStats, @@ -381,6 +383,7 @@ "Container", "ContentItem", "ContentLocation", + "ContentMetadata", "CreateConnectionRequest", "CreateDeidentifyTemplateRequest", "CreateDiscoveryConfigRequest", @@ -506,6 +509,7 @@ "InspectTemplate", "JobTrigger", "KeyValueMetadataLabel", + "KeyValueMetadataProperty", "KmsWrappedCryptoKey", "LargeCustomDictionaryConfig", "LargeCustomDictionaryStats", diff --git a/packages/google-cloud-dlp/google/cloud/dlp_v2/__init__.py b/packages/google-cloud-dlp/google/cloud/dlp_v2/__init__.py index 752d58fdad89..91f7bc0c26b8 100644 --- a/packages/google-cloud-dlp/google/cloud/dlp_v2/__init__.py +++ b/packages/google-cloud-dlp/google/cloud/dlp_v2/__init__.py @@ -73,6 +73,7 @@ Container, ContentItem, ContentLocation, + ContentMetadata, ContentOption, CreateConnectionRequest, CreateDeidentifyTemplateRequest, @@ -203,6 +204,7 @@ InspectTemplate, JobTrigger, KeyValueMetadataLabel, + KeyValueMetadataProperty, KmsWrappedCryptoKey, LargeCustomDictionaryConfig, LargeCustomDictionaryStats, @@ -497,6 +499,7 @@ def _get_version(dependency_name): "Container", "ContentItem", "ContentLocation", + "ContentMetadata", "ContentOption", "CreateConnectionRequest", "CreateDeidentifyTemplateRequest", @@ -637,6 +640,7 @@ def _get_version(dependency_name): "JobTrigger", "Key", "KeyValueMetadataLabel", + "KeyValueMetadataProperty", "KindExpression", "KmsWrappedCryptoKey", "LargeCustomDictionaryConfig", diff --git a/packages/google-cloud-dlp/google/cloud/dlp_v2/types/__init__.py b/packages/google-cloud-dlp/google/cloud/dlp_v2/types/__init__.py index e932ddc37626..58af7da344d8 100644 --- a/packages/google-cloud-dlp/google/cloud/dlp_v2/types/__init__.py +++ b/packages/google-cloud-dlp/google/cloud/dlp_v2/types/__init__.py @@ -56,6 +56,7 @@ Container, ContentItem, ContentLocation, + ContentMetadata, ContentOption, CreateConnectionRequest, CreateDeidentifyTemplateRequest, @@ -186,6 +187,7 @@ InspectTemplate, JobTrigger, KeyValueMetadataLabel, + KeyValueMetadataProperty, KmsWrappedCryptoKey, LargeCustomDictionaryConfig, LargeCustomDictionaryStats, @@ -372,6 +374,7 @@ "Container", "ContentItem", "ContentLocation", + "ContentMetadata", "CreateConnectionRequest", "CreateDeidentifyTemplateRequest", "CreateDiscoveryConfigRequest", @@ -497,6 +500,7 @@ "InspectTemplate", "JobTrigger", "KeyValueMetadataLabel", + "KeyValueMetadataProperty", "KmsWrappedCryptoKey", "LargeCustomDictionaryConfig", "LargeCustomDictionaryStats", diff --git a/packages/google-cloud-dlp/google/cloud/dlp_v2/types/dlp.py b/packages/google-cloud-dlp/google/cloud/dlp_v2/types/dlp.py index d3a32195b1af..fbd6907f7bb2 100644 --- a/packages/google-cloud-dlp/google/cloud/dlp_v2/types/dlp.py +++ b/packages/google-cloud-dlp/google/cloud/dlp_v2/types/dlp.py @@ -65,7 +65,9 @@ "InspectConfig", "ByteContentItem", "ContentItem", + "ContentMetadata", "Table", + "KeyValueMetadataProperty", "InspectResult", "Finding", "Location", @@ -684,11 +686,14 @@ class MetadataType(proto.Enum): Storage. CONTENT_METADATA (3): Metadata extracted from the files. + CLIENT_PROVIDED_METADATA (4): + Metadata provided by the client. """ METADATATYPE_UNSPECIFIED = 0 STORAGE_METADATA = 2 CONTENT_METADATA = 3 + CLIENT_PROVIDED_METADATA = 4 class InfoTypeSupportedBy(proto.Enum): @@ -1630,6 +1635,8 @@ class ContentItem(proto.Message): ``data``. This field is a member of `oneof`_ ``data_item``. + content_metadata (google.cloud.dlp_v2.types.ContentMetadata): + User provided metadata for the content. """ value: str = proto.Field( @@ -1649,6 +1656,27 @@ class ContentItem(proto.Message): oneof="data_item", message="ByteContentItem", ) + content_metadata: "ContentMetadata" = proto.Field( + proto.MESSAGE, + number=6, + message="ContentMetadata", + ) + + +class ContentMetadata(proto.Message): + r"""Metadata on content to be scanned. + + Attributes: + properties (MutableSequence[google.cloud.dlp_v2.types.KeyValueMetadataProperty]): + User provided key-value pairs of content + metadata. + """ + + properties: MutableSequence["KeyValueMetadataProperty"] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message="KeyValueMetadataProperty", + ) class Table(proto.Message): @@ -1690,6 +1718,26 @@ class Row(proto.Message): ) +class KeyValueMetadataProperty(proto.Message): + r"""A key-value pair in the Metadata. + + Attributes: + key (str): + The key of the property. + value (str): + The value of the property. + """ + + key: str = proto.Field( + proto.STRING, + number=1, + ) + value: str = proto.Field( + proto.STRING, + number=2, + ) + + class InspectResult(proto.Message): r"""All the findings for a single scanned item. 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 97deabfae555..2afc14a00ea5 100644 --- a/packages/google-cloud-memorystore/google/cloud/memorystore_v1beta/__init__.py +++ b/packages/google-cloud-memorystore/google/cloud/memorystore_v1beta/__init__.py @@ -38,6 +38,7 @@ DiscoveryEndpoint, GetCertificateAuthorityRequest, GetInstanceRequest, + GetSharedRegionalCertificateAuthorityRequest, Instance, ListInstancesRequest, ListInstancesResponse, @@ -47,6 +48,7 @@ PscAutoConnection, PscConnection, PscConnectionStatus, + SharedRegionalCertificateAuthority, UpdateInstanceRequest, ZoneDistributionConfig, ) @@ -153,6 +155,7 @@ def _get_version(dependency_name): "DiscoveryEndpoint", "GetCertificateAuthorityRequest", "GetInstanceRequest", + "GetSharedRegionalCertificateAuthorityRequest", "Instance", "ListInstancesRequest", "ListInstancesResponse", @@ -163,6 +166,7 @@ def _get_version(dependency_name): "PscAutoConnection", "PscConnection", "PscConnectionStatus", + "SharedRegionalCertificateAuthority", "UpdateInstanceRequest", "ZoneDistributionConfig", ) diff --git a/packages/google-cloud-memorystore/google/cloud/memorystore_v1beta/gapic_metadata.json b/packages/google-cloud-memorystore/google/cloud/memorystore_v1beta/gapic_metadata.json index 0951913c6fff..084be27f2365 100644 --- a/packages/google-cloud-memorystore/google/cloud/memorystore_v1beta/gapic_metadata.json +++ b/packages/google-cloud-memorystore/google/cloud/memorystore_v1beta/gapic_metadata.json @@ -30,6 +30,11 @@ "get_instance" ] }, + "GetSharedRegionalCertificateAuthority": { + "methods": [ + "get_shared_regional_certificate_authority" + ] + }, "ListInstances": { "methods": [ "list_instances" diff --git a/packages/google-cloud-memorystore/google/cloud/memorystore_v1beta/services/memorystore/client.py b/packages/google-cloud-memorystore/google/cloud/memorystore_v1beta/services/memorystore/client.py index c6088b577e7d..f9498342827e 100644 --- a/packages/google-cloud-memorystore/google/cloud/memorystore_v1beta/services/memorystore/client.py +++ b/packages/google-cloud-memorystore/google/cloud/memorystore_v1beta/services/memorystore/client.py @@ -230,6 +230,28 @@ def transport(self) -> MemorystoreTransport: """ return self._transport + @staticmethod + def ca_pool_path( + project: str, + location: str, + ca_pool: str, + ) -> str: + """Returns a fully-qualified ca_pool string.""" + return "projects/{project}/locations/{location}/caPools/{ca_pool}".format( + project=project, + location=location, + ca_pool=ca_pool, + ) + + @staticmethod + def parse_ca_pool_path(path: str) -> Dict[str, str]: + """Parses a ca_pool path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/caPools/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + @staticmethod def certificate_authority_path( project: str, @@ -337,6 +359,26 @@ def parse_service_attachment_path(path: str) -> Dict[str, str]: ) return m.groupdict() if m else {} + @staticmethod + def shared_regional_certificate_authority_path( + project: str, + location: str, + ) -> str: + """Returns a fully-qualified shared_regional_certificate_authority string.""" + return "projects/{project}/locations/{location}/sharedRegionalCertificateAuthority".format( + project=project, + location=location, + ) + + @staticmethod + def parse_shared_regional_certificate_authority_path(path: str) -> Dict[str, str]: + """Parses a shared_regional_certificate_authority path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/sharedRegionalCertificateAuthority$", + path, + ) + return m.groupdict() if m else {} + @staticmethod def common_billing_account_path( billing_account: str, @@ -1582,6 +1624,123 @@ def sample_get_certificate_authority(): # Done; return the response. return response + def get_shared_regional_certificate_authority( + self, + request: Optional[ + Union[memorystore.GetSharedRegionalCertificateAuthorityRequest, dict] + ] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> memorystore.SharedRegionalCertificateAuthority: + r"""Gets the details of shared regional certificate + authority information for Memorystore instance. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import memorystore_v1beta + + def sample_get_shared_regional_certificate_authority(): + # Create a client + client = memorystore_v1beta.MemorystoreClient() + + # Initialize request argument(s) + request = memorystore_v1beta.GetSharedRegionalCertificateAuthorityRequest( + name="name_value", + ) + + # Make the request + response = client.get_shared_regional_certificate_authority(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.memorystore_v1beta.types.GetSharedRegionalCertificateAuthorityRequest, dict]): + The request object. Request for + [GetSharedRegionalCertificateAuthority][google.cloud.memorystore.v1beta.Memorystore.GetSharedRegionalCertificateAuthority]. + name (str): + Required. Regional certificate authority resource name + using the form: + ``projects/{project}/locations/{location}/sharedRegionalCertificateAuthority`` + where ``location_id`` refers to a Google Cloud region. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.memorystore_v1beta.types.SharedRegionalCertificateAuthority: + Shared regional certificate authority + for an instance. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance( + request, memorystore.GetSharedRegionalCertificateAuthorityRequest + ): + request = memorystore.GetSharedRegionalCertificateAuthorityRequest(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_shared_regional_certificate_authority + ] + + # 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) -> "MemorystoreClient": return self diff --git a/packages/google-cloud-memorystore/google/cloud/memorystore_v1beta/services/memorystore/transports/base.py b/packages/google-cloud-memorystore/google/cloud/memorystore_v1beta/services/memorystore/transports/base.py index 4f568a208d4e..2240c070c88d 100644 --- a/packages/google-cloud-memorystore/google/cloud/memorystore_v1beta/services/memorystore/transports/base.py +++ b/packages/google-cloud-memorystore/google/cloud/memorystore_v1beta/services/memorystore/transports/base.py @@ -201,6 +201,11 @@ def _prep_wrapped_messages(self, client_info): default_timeout=60.0, client_info=client_info, ), + self.get_shared_regional_certificate_authority: gapic_v1.method.wrap_method( + self.get_shared_regional_certificate_authority, + default_timeout=None, + client_info=client_info, + ), self.get_location: gapic_v1.method.wrap_method( self.get_location, default_timeout=None, @@ -307,6 +312,18 @@ def get_certificate_authority( ]: raise NotImplementedError() + @property + def get_shared_regional_certificate_authority( + self, + ) -> Callable[ + [memorystore.GetSharedRegionalCertificateAuthorityRequest], + Union[ + memorystore.SharedRegionalCertificateAuthority, + Awaitable[memorystore.SharedRegionalCertificateAuthority], + ], + ]: + raise NotImplementedError() + @property def list_operations( self, diff --git a/packages/google-cloud-memorystore/google/cloud/memorystore_v1beta/services/memorystore/transports/rest.py b/packages/google-cloud-memorystore/google/cloud/memorystore_v1beta/services/memorystore/transports/rest.py index 2732c4a9eec0..8a4dc06dbddb 100644 --- a/packages/google-cloud-memorystore/google/cloud/memorystore_v1beta/services/memorystore/transports/rest.py +++ b/packages/google-cloud-memorystore/google/cloud/memorystore_v1beta/services/memorystore/transports/rest.py @@ -106,6 +106,14 @@ def post_get_instance(self, response): logging.log(f"Received response: {response}") return response + def pre_get_shared_regional_certificate_authority(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_shared_regional_certificate_authority(self, response): + logging.log(f"Received response: {response}") + return response + def pre_list_instances(self, request, metadata): logging.log(f"Received request: {request}") return request, metadata @@ -319,6 +327,58 @@ def post_get_instance_with_metadata( """ return response, metadata + def pre_get_shared_regional_certificate_authority( + self, + request: memorystore.GetSharedRegionalCertificateAuthorityRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + memorystore.GetSharedRegionalCertificateAuthorityRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for get_shared_regional_certificate_authority + + Override in a subclass to manipulate the request or metadata + before they are sent to the Memorystore server. + """ + return request, metadata + + def post_get_shared_regional_certificate_authority( + self, response: memorystore.SharedRegionalCertificateAuthority + ) -> memorystore.SharedRegionalCertificateAuthority: + """Post-rpc interceptor for get_shared_regional_certificate_authority + + DEPRECATED. Please use the `post_get_shared_regional_certificate_authority_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the Memorystore server but before + it is returned to user code. This `post_get_shared_regional_certificate_authority` interceptor runs + before the `post_get_shared_regional_certificate_authority_with_metadata` interceptor. + """ + return response + + def post_get_shared_regional_certificate_authority_with_metadata( + self, + response: memorystore.SharedRegionalCertificateAuthority, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + memorystore.SharedRegionalCertificateAuthority, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Post-rpc interceptor for get_shared_regional_certificate_authority + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the Memorystore server but before it is returned to user code. + + We recommend only using this `post_get_shared_regional_certificate_authority_with_metadata` + interceptor in new development instead of the `post_get_shared_regional_certificate_authority` interceptor. + When both interceptors are used, this `post_get_shared_regional_certificate_authority_with_metadata` interceptor runs after the + `post_get_shared_regional_certificate_authority` interceptor. The (possibly modified) response returned by + `post_get_shared_regional_certificate_authority` will be passed to + `post_get_shared_regional_certificate_authority_with_metadata`. + """ + return response, metadata + def pre_list_instances( self, request: memorystore.ListInstancesRequest, @@ -1302,6 +1362,165 @@ def __call__( ) return resp + class _GetSharedRegionalCertificateAuthority( + _BaseMemorystoreRestTransport._BaseGetSharedRegionalCertificateAuthority, + MemorystoreRestStub, + ): + def __hash__(self): + return hash( + "MemorystoreRestTransport.GetSharedRegionalCertificateAuthority" + ) + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: memorystore.GetSharedRegionalCertificateAuthorityRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> memorystore.SharedRegionalCertificateAuthority: + r"""Call the get shared regional + certificate authority method over HTTP. + + Args: + request (~.memorystore.GetSharedRegionalCertificateAuthorityRequest): + The request object. Request for + [GetSharedRegionalCertificateAuthority][google.cloud.memorystore.v1beta.Memorystore.GetSharedRegionalCertificateAuthority]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.memorystore.SharedRegionalCertificateAuthority: + Shared regional certificate authority + for an instance. + + """ + + http_options = _BaseMemorystoreRestTransport._BaseGetSharedRegionalCertificateAuthority._get_http_options() + + request, metadata = ( + self._interceptor.pre_get_shared_regional_certificate_authority( + request, metadata + ) + ) + transcoded_request = _BaseMemorystoreRestTransport._BaseGetSharedRegionalCertificateAuthority._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = _BaseMemorystoreRestTransport._BaseGetSharedRegionalCertificateAuthority._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.memorystore_v1beta.MemorystoreClient.GetSharedRegionalCertificateAuthority", + extra={ + "serviceName": "google.cloud.memorystore.v1beta.Memorystore", + "rpcName": "GetSharedRegionalCertificateAuthority", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = MemorystoreRestTransport._GetSharedRegionalCertificateAuthority._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = memorystore.SharedRegionalCertificateAuthority() + pb_resp = memorystore.SharedRegionalCertificateAuthority.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_get_shared_regional_certificate_authority( + resp + ) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = ( + self._interceptor.post_get_shared_regional_certificate_authority_with_metadata( + resp, response_metadata + ) + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = ( + memorystore.SharedRegionalCertificateAuthority.to_json(response) + ) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.memorystore_v1beta.MemorystoreClient.get_shared_regional_certificate_authority", + extra={ + "serviceName": "google.cloud.memorystore.v1beta.Memorystore", + "rpcName": "GetSharedRegionalCertificateAuthority", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + class _ListInstances( _BaseMemorystoreRestTransport._BaseListInstances, MemorystoreRestStub ): @@ -1637,6 +1856,19 @@ def get_instance( # In C++ this would require a dynamic_cast return self._GetInstance(self._session, self._host, self._interceptor) # type: ignore + @property + def get_shared_regional_certificate_authority( + self, + ) -> Callable[ + [memorystore.GetSharedRegionalCertificateAuthorityRequest], + memorystore.SharedRegionalCertificateAuthority, + ]: + # 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._GetSharedRegionalCertificateAuthority( + self._session, self._host, self._interceptor + ) # type: ignore + @property def list_instances( self, diff --git a/packages/google-cloud-memorystore/google/cloud/memorystore_v1beta/services/memorystore/transports/rest_base.py b/packages/google-cloud-memorystore/google/cloud/memorystore_v1beta/services/memorystore/transports/rest_base.py index 8cd96582440d..2d12561aeaa0 100644 --- a/packages/google-cloud-memorystore/google/cloud/memorystore_v1beta/services/memorystore/transports/rest_base.py +++ b/packages/google-cloud-memorystore/google/cloud/memorystore_v1beta/services/memorystore/transports/rest_base.py @@ -289,6 +289,55 @@ def _get_query_params_json(transcoded_request): query_params["$alt"] = "json;enum-encoding=int" return query_params + class _BaseGetSharedRegionalCertificateAuthority: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1beta/{name=projects/*/locations/*/sharedRegionalCertificateAuthority}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = memorystore.GetSharedRegionalCertificateAuthorityRequest.pb( + request + ) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseMemorystoreRestTransport._BaseGetSharedRegionalCertificateAuthority._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + class _BaseListInstances: def __hash__(self): # pragma: NO COVER return NotImplementedError("__hash__ must be implemented.") 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 412ec4452e77..9b9ff31bc2d5 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 @@ -21,6 +21,7 @@ DiscoveryEndpoint, GetCertificateAuthorityRequest, GetInstanceRequest, + GetSharedRegionalCertificateAuthorityRequest, Instance, ListInstancesRequest, ListInstancesResponse, @@ -30,6 +31,7 @@ PscAutoConnection, PscConnection, PscConnectionStatus, + SharedRegionalCertificateAuthority, UpdateInstanceRequest, ZoneDistributionConfig, ) @@ -41,6 +43,7 @@ "DiscoveryEndpoint", "GetCertificateAuthorityRequest", "GetInstanceRequest", + "GetSharedRegionalCertificateAuthorityRequest", "Instance", "ListInstancesRequest", "ListInstancesResponse", @@ -49,6 +52,7 @@ "PersistenceConfig", "PscAutoConnection", "PscConnection", + "SharedRegionalCertificateAuthority", "UpdateInstanceRequest", "ZoneDistributionConfig", "ConnectionType", 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 1ea094b0a8d8..5773aba0a9ff 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 @@ -41,6 +41,8 @@ "DeleteInstanceRequest", "GetCertificateAuthorityRequest", "CertificateAuthority", + "SharedRegionalCertificateAuthority", + "GetSharedRegionalCertificateAuthorityRequest", "OperationMetadata", }, ) @@ -161,6 +163,23 @@ class Instance(proto.Message): Optional. Endpoints for the instance. mode (google.cloud.memorystore_v1beta.types.Instance.Mode): Optional. The mode config for the instance. + server_ca_mode (google.cloud.memorystore_v1beta.types.Instance.ServerCaMode): + Optional. Immutable. The Server CA mode for + the instance. + + This field is a member of `oneof`_ ``_server_ca_mode``. + server_ca_pool (str): + Optional. Immutable. The customer-managed CA pool for the + instance. Only applicable if the Server CA mode is + CUSTOMER_MANAGED_CAS_CA. Format: + "projects/{project}/locations/{region}/caPools/{ca_pool}". + + This field is a member of `oneof`_ ``_server_ca_pool``. + rotate_server_certificate (bool): + Optional. Input only. Rotate the server + certificates. + + This field is a member of `oneof`_ ``_rotate_server_certificate``. """ class State(proto.Enum): @@ -262,6 +281,37 @@ class Mode(proto.Enum): CLUSTER = 2 CLUSTER_DISABLED = 4 + class ServerCaMode(proto.Enum): + r"""The Server CA mode for the instance. + + Values: + SERVER_CA_MODE_UNSPECIFIED (0): + Server CA mode not specified. + GOOGLE_MANAGED_PER_INSTANCE_CA (1): + Each instance has its own Google-managed CA. + GOOGLE_MANAGED_SHARED_CA (2): + The instance uses a Google-managed shared CA + for the instance's region. + CUSTOMER_MANAGED_CAS_CA (3): + The instance uses a customer-managed CA from + CAS. + SERVER_CA_MODE_GOOGLE_MANAGED_PER_INSTANCE_CA (1): + Deprecated: Use GOOGLE_MANAGED_PER_INSTANCE_CA instead. + SERVER_CA_MODE_GOOGLE_MANAGED_SHARED_CA (2): + Deprecated: Use GOOGLE_MANAGED_SHARED_CA instead. + SERVER_CA_MODE_CUSTOMER_MANAGED_CAS_CA (3): + Deprecated: Use CUSTOMER_MANAGED_CAS_CA instead. + """ + + _pb_options = {"allow_alias": True} + SERVER_CA_MODE_UNSPECIFIED = 0 + GOOGLE_MANAGED_PER_INSTANCE_CA = 1 + GOOGLE_MANAGED_SHARED_CA = 2 + CUSTOMER_MANAGED_CAS_CA = 3 + SERVER_CA_MODE_GOOGLE_MANAGED_PER_INSTANCE_CA = 1 + SERVER_CA_MODE_GOOGLE_MANAGED_SHARED_CA = 2 + SERVER_CA_MODE_CUSTOMER_MANAGED_CAS_CA = 3 + class StateInfo(proto.Message): r"""Additional information about the state of the instance. @@ -473,6 +523,22 @@ class ConnectionDetail(proto.Message): number=26, enum=Mode, ) + server_ca_mode: ServerCaMode = proto.Field( + proto.ENUM, + number=56, + optional=True, + enum=ServerCaMode, + ) + server_ca_pool: str = proto.Field( + proto.STRING, + number=57, + optional=True, + ) + rotate_server_certificate: bool = proto.Field( + proto.BOOL, + number=58, + optional=True, + ) class PscAutoConnection(proto.Message): @@ -1179,6 +1245,86 @@ class CertChain(proto.Message): ) +class SharedRegionalCertificateAuthority(proto.Message): + r"""Shared regional certificate authority for an instance. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + managed_server_ca (google.cloud.memorystore_v1beta.types.SharedRegionalCertificateAuthority.RegionalManagedCertificateAuthority): + CA certificate chains for memorystore managed + server authentication. + + This field is a member of `oneof`_ ``server_ca``. + name (str): + Identifier. Unique name of the resource in this scope + including project and location using the form: + ``projects/{project}/locations/{location}/sharedRegionalCertificateAuthority`` + """ + + class RegionalManagedCertificateAuthority(proto.Message): + r"""CA certificate chains for memorystore managed server + authentication. + + Attributes: + ca_certs (MutableSequence[google.cloud.memorystore_v1beta.types.SharedRegionalCertificateAuthority.RegionalManagedCertificateAuthority.RegionalCertChain]): + The PEM encoded CA certificate chains for + memorystore managed server authentication + """ + + class RegionalCertChain(proto.Message): + r"""The certificates that form the CA chain, from leaf to root + order. + + Attributes: + certificates (MutableSequence[str]): + The certificates that form the CA chain, from + leaf to root order. + """ + + certificates: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=1, + ) + + ca_certs: MutableSequence[ + "SharedRegionalCertificateAuthority.RegionalManagedCertificateAuthority.RegionalCertChain" + ] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message="SharedRegionalCertificateAuthority.RegionalManagedCertificateAuthority.RegionalCertChain", + ) + + managed_server_ca: RegionalManagedCertificateAuthority = proto.Field( + proto.MESSAGE, + number=2, + oneof="server_ca", + message=RegionalManagedCertificateAuthority, + ) + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class GetSharedRegionalCertificateAuthorityRequest(proto.Message): + r"""Request for + [GetSharedRegionalCertificateAuthority][google.cloud.memorystore.v1beta.Memorystore.GetSharedRegionalCertificateAuthority]. + + Attributes: + name (str): + Required. Regional certificate authority resource name using + the form: + ``projects/{project}/locations/{location}/sharedRegionalCertificateAuthority`` + where ``location_id`` refers to a Google Cloud region. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + class OperationMetadata(proto.Message): r"""Represents the metadata of a long-running operation. diff --git a/packages/google-cloud-memorystore/samples/generated_samples/memorystore_v1beta_generated_memorystore_get_shared_regional_certificate_authority_sync.py b/packages/google-cloud-memorystore/samples/generated_samples/memorystore_v1beta_generated_memorystore_get_shared_regional_certificate_authority_sync.py new file mode 100644 index 000000000000..c7734f2f3d6a --- /dev/null +++ b/packages/google-cloud-memorystore/samples/generated_samples/memorystore_v1beta_generated_memorystore_get_shared_regional_certificate_authority_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetSharedRegionalCertificateAuthority +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-memorystore + + +# [START memorystore_v1beta_generated_Memorystore_GetSharedRegionalCertificateAuthority_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import memorystore_v1beta + + +def sample_get_shared_regional_certificate_authority(): + # Create a client + client = memorystore_v1beta.MemorystoreClient() + + # Initialize request argument(s) + request = memorystore_v1beta.GetSharedRegionalCertificateAuthorityRequest( + name="name_value", + ) + + # Make the request + response = client.get_shared_regional_certificate_authority(request=request) + + # Handle the response + print(response) + + +# [END memorystore_v1beta_generated_Memorystore_GetSharedRegionalCertificateAuthority_sync] diff --git a/packages/google-cloud-memorystore/samples/generated_samples/snippet_metadata_google.cloud.memorystore.v1beta.json b/packages/google-cloud-memorystore/samples/generated_samples/snippet_metadata_google.cloud.memorystore.v1beta.json index 317dea8769ee..39b10f86ecdd 100644 --- a/packages/google-cloud-memorystore/samples/generated_samples/snippet_metadata_google.cloud.memorystore.v1beta.json +++ b/packages/google-cloud-memorystore/samples/generated_samples/snippet_metadata_google.cloud.memorystore.v1beta.json @@ -339,6 +339,86 @@ ], "title": "memorystore_v1beta_generated_memorystore_get_instance_sync.py" }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.memorystore_v1beta.MemorystoreClient", + "shortName": "MemorystoreClient" + }, + "fullName": "google.cloud.memorystore_v1beta.MemorystoreClient.get_shared_regional_certificate_authority", + "method": { + "fullName": "google.cloud.memorystore.v1beta.Memorystore.GetSharedRegionalCertificateAuthority", + "service": { + "fullName": "google.cloud.memorystore.v1beta.Memorystore", + "shortName": "Memorystore" + }, + "shortName": "GetSharedRegionalCertificateAuthority" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.memorystore_v1beta.types.GetSharedRegionalCertificateAuthorityRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.memorystore_v1beta.types.SharedRegionalCertificateAuthority", + "shortName": "get_shared_regional_certificate_authority" + }, + "description": "Sample for GetSharedRegionalCertificateAuthority", + "file": "memorystore_v1beta_generated_memorystore_get_shared_regional_certificate_authority_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "memorystore_v1beta_generated_Memorystore_GetSharedRegionalCertificateAuthority_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "memorystore_v1beta_generated_memorystore_get_shared_regional_certificate_authority_sync.py" + }, { "canonical": true, "clientMethod": { 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 683ac15482af..9d4a7778253f 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 @@ -2345,6 +2345,203 @@ def test_get_certificate_authority_rest_flattened_error(transport: str = "rest") ) +def test_get_shared_regional_certificate_authority_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = MemorystoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.get_shared_regional_certificate_authority + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.get_shared_regional_certificate_authority + ] = mock_rpc + + request = {} + client.get_shared_regional_certificate_authority(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_shared_regional_certificate_authority(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_get_shared_regional_certificate_authority_rest_required_fields( + request_type=memorystore.GetSharedRegionalCertificateAuthorityRequest, +): + transport_class = transports.MemorystoreRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get_shared_regional_certificate_authority._get_unset_required_fields( + jsonified_request + ) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get_shared_regional_certificate_authority._get_unset_required_fields( + jsonified_request + ) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + + client = MemorystoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = memorystore.SharedRegionalCertificateAuthority() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "get", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = memorystore.SharedRegionalCertificateAuthority.pb( + return_value + ) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.get_shared_regional_certificate_authority(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_get_shared_regional_certificate_authority_rest_unset_required_fields(): + transport = transports.MemorystoreRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = ( + transport.get_shared_regional_certificate_authority._get_unset_required_fields( + {} + ) + ) + assert set(unset_fields) == (set(()) & set(("name",))) + + +def test_get_shared_regional_certificate_authority_rest_flattened(): + client = MemorystoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = memorystore.SharedRegionalCertificateAuthority() + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/sharedRegionalCertificateAuthority" + } + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = memorystore.SharedRegionalCertificateAuthority.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.get_shared_regional_certificate_authority(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1beta/{name=projects/*/locations/*/sharedRegionalCertificateAuthority}" + % client.transport._host, + args[1], + ) + + +def test_get_shared_regional_certificate_authority_rest_flattened_error( + transport: str = "rest", +): + client = MemorystoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_shared_regional_certificate_authority( + memorystore.GetSharedRegionalCertificateAuthorityRequest(), + name="name_value", + ) + + def test_credentials_transport_error(): # It is an error to provide credentials and a transport instance. transport = transports.MemorystoreRestTransport( @@ -2614,6 +2811,9 @@ def test_get_instance_rest_call_success(request_type): engine_version="engine_version_value", deletion_protection_enabled=True, mode=memorystore.Instance.Mode.STANDALONE, + server_ca_mode=memorystore.Instance.ServerCaMode.GOOGLE_MANAGED_PER_INSTANCE_CA, + server_ca_pool="server_ca_pool_value", + rotate_server_certificate=True, ) # Wrap the value into a proper Response obj @@ -2647,6 +2847,12 @@ def test_get_instance_rest_call_success(request_type): assert response.engine_version == "engine_version_value" assert response.deletion_protection_enabled is True assert response.mode == memorystore.Instance.Mode.STANDALONE + assert ( + response.server_ca_mode + == memorystore.Instance.ServerCaMode.GOOGLE_MANAGED_PER_INSTANCE_CA + ) + assert response.server_ca_pool == "server_ca_pool_value" + assert response.rotate_server_certificate is True @pytest.mark.parametrize("null_interceptor", [True, False]) @@ -2812,6 +3018,9 @@ def test_create_instance_rest_call_success(request_type): } ], "mode": 1, + "server_ca_mode": 1, + "server_ca_pool": "server_ca_pool_value", + "rotate_server_certificate": 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 @@ -3070,6 +3279,9 @@ def test_update_instance_rest_call_success(request_type): } ], "mode": 1, + "server_ca_mode": 1, + "server_ca_pool": "server_ca_pool_value", + "rotate_server_certificate": 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 @@ -3481,6 +3693,148 @@ def test_get_certificate_authority_rest_interceptors(null_interceptor): post_with_metadata.assert_called_once() +def test_get_shared_regional_certificate_authority_rest_bad_request( + request_type=memorystore.GetSharedRegionalCertificateAuthorityRequest, +): + client = MemorystoreClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/sharedRegionalCertificateAuthority" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.get_shared_regional_certificate_authority(request) + + +@pytest.mark.parametrize( + "request_type", + [ + memorystore.GetSharedRegionalCertificateAuthorityRequest, + dict, + ], +) +def test_get_shared_regional_certificate_authority_rest_call_success(request_type): + client = MemorystoreClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/sharedRegionalCertificateAuthority" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = memorystore.SharedRegionalCertificateAuthority( + name="name_value", + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = memorystore.SharedRegionalCertificateAuthority.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.get_shared_regional_certificate_authority(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, memorystore.SharedRegionalCertificateAuthority) + assert response.name == "name_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_shared_regional_certificate_authority_rest_interceptors(null_interceptor): + transport = transports.MemorystoreRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.MemorystoreRestInterceptor(), + ) + client = MemorystoreClient(transport=transport) + + with ( + mock.patch.object(type(client.transport._session), "request") as req, + mock.patch.object(path_template, "transcode") as transcode, + mock.patch.object( + transports.MemorystoreRestInterceptor, + "post_get_shared_regional_certificate_authority", + ) as post, + mock.patch.object( + transports.MemorystoreRestInterceptor, + "post_get_shared_regional_certificate_authority_with_metadata", + ) as post_with_metadata, + mock.patch.object( + transports.MemorystoreRestInterceptor, + "pre_get_shared_regional_certificate_authority", + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = memorystore.GetSharedRegionalCertificateAuthorityRequest.pb( + memorystore.GetSharedRegionalCertificateAuthorityRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = memorystore.SharedRegionalCertificateAuthority.to_json( + memorystore.SharedRegionalCertificateAuthority() + ) + req.return_value.content = return_value + + request = memorystore.GetSharedRegionalCertificateAuthorityRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = memorystore.SharedRegionalCertificateAuthority() + post_with_metadata.return_value = ( + memorystore.SharedRegionalCertificateAuthority(), + metadata, + ) + + client.get_shared_regional_certificate_authority( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + def test_get_location_rest_bad_request(request_type=locations_pb2.GetLocationRequest): client = MemorystoreClient( credentials=ga_credentials.AnonymousCredentials(), @@ -3984,6 +4338,28 @@ def test_get_certificate_authority_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_shared_regional_certificate_authority_empty_call_rest(): + client = MemorystoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_shared_regional_certificate_authority), "__call__" + ) as call: + client.get_shared_regional_certificate_authority(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = memorystore.GetSharedRegionalCertificateAuthorityRequest() + + assert args[0] == request_msg + + def test_memorystore_rest_lro_client(): client = MemorystoreClient( credentials=ga_credentials.AnonymousCredentials(), @@ -4029,6 +4405,7 @@ def test_memorystore_base_transport(): "update_instance", "delete_instance", "get_certificate_authority", + "get_shared_regional_certificate_authority", "get_location", "list_locations", "get_operation", @@ -4195,12 +4572,41 @@ def test_memorystore_client_transport_session_collision(transport_name): session1 = client1.transport.get_certificate_authority._session session2 = client2.transport.get_certificate_authority._session assert session1 != session2 + session1 = client1.transport.get_shared_regional_certificate_authority._session + session2 = client2.transport.get_shared_regional_certificate_authority._session + assert session1 != session2 -def test_certificate_authority_path(): +def test_ca_pool_path(): project = "squid" location = "clam" - instance = "whelk" + ca_pool = "whelk" + expected = "projects/{project}/locations/{location}/caPools/{ca_pool}".format( + project=project, + location=location, + ca_pool=ca_pool, + ) + actual = MemorystoreClient.ca_pool_path(project, location, ca_pool) + assert expected == actual + + +def test_parse_ca_pool_path(): + expected = { + "project": "octopus", + "location": "oyster", + "ca_pool": "nudibranch", + } + path = MemorystoreClient.ca_pool_path(**expected) + + # Check that the path construction is reversible. + actual = MemorystoreClient.parse_ca_pool_path(path) + assert expected == actual + + +def test_certificate_authority_path(): + project = "cuttlefish" + location = "mussel" + instance = "winkle" expected = "projects/{project}/locations/{location}/instances/{instance}/certificateAuthority".format( project=project, location=location, @@ -4212,9 +4618,9 @@ def test_certificate_authority_path(): def test_parse_certificate_authority_path(): expected = { - "project": "octopus", - "location": "oyster", - "instance": "nudibranch", + "project": "nautilus", + "location": "scallop", + "instance": "abalone", } path = MemorystoreClient.certificate_authority_path(**expected) @@ -4224,9 +4630,9 @@ def test_parse_certificate_authority_path(): def test_forwarding_rule_path(): - project = "cuttlefish" - region = "mussel" - forwarding_rule = "winkle" + project = "squid" + region = "clam" + forwarding_rule = "whelk" expected = ( "projects/{project}/regions/{region}/forwardingRules/{forwarding_rule}".format( project=project, @@ -4240,9 +4646,9 @@ def test_forwarding_rule_path(): def test_parse_forwarding_rule_path(): expected = { - "project": "nautilus", - "region": "scallop", - "forwarding_rule": "abalone", + "project": "octopus", + "region": "oyster", + "forwarding_rule": "nudibranch", } path = MemorystoreClient.forwarding_rule_path(**expected) @@ -4252,9 +4658,9 @@ def test_parse_forwarding_rule_path(): def test_instance_path(): - project = "squid" - location = "clam" - instance = "whelk" + project = "cuttlefish" + location = "mussel" + instance = "winkle" expected = "projects/{project}/locations/{location}/instances/{instance}".format( project=project, location=location, @@ -4266,9 +4672,9 @@ def test_instance_path(): def test_parse_instance_path(): expected = { - "project": "octopus", - "location": "oyster", - "instance": "nudibranch", + "project": "nautilus", + "location": "scallop", + "instance": "abalone", } path = MemorystoreClient.instance_path(**expected) @@ -4278,8 +4684,8 @@ def test_parse_instance_path(): def test_network_path(): - project = "cuttlefish" - network = "mussel" + project = "squid" + network = "clam" expected = "projects/{project}/global/networks/{network}".format( project=project, network=network, @@ -4290,8 +4696,8 @@ def test_network_path(): def test_parse_network_path(): expected = { - "project": "winkle", - "network": "nautilus", + "project": "whelk", + "network": "octopus", } path = MemorystoreClient.network_path(**expected) @@ -4301,9 +4707,9 @@ def test_parse_network_path(): def test_service_attachment_path(): - project = "scallop" - region = "abalone" - service_attachment = "squid" + project = "oyster" + region = "nudibranch" + service_attachment = "cuttlefish" expected = "projects/{project}/regions/{region}/serviceAttachments/{service_attachment}".format( project=project, region=region, @@ -4317,9 +4723,9 @@ def test_service_attachment_path(): def test_parse_service_attachment_path(): expected = { - "project": "clam", - "region": "whelk", - "service_attachment": "octopus", + "project": "mussel", + "region": "winkle", + "service_attachment": "nautilus", } path = MemorystoreClient.service_attachment_path(**expected) @@ -4328,8 +4734,33 @@ def test_parse_service_attachment_path(): assert expected == actual +def test_shared_regional_certificate_authority_path(): + project = "scallop" + location = "abalone" + expected = "projects/{project}/locations/{location}/sharedRegionalCertificateAuthority".format( + project=project, + location=location, + ) + actual = MemorystoreClient.shared_regional_certificate_authority_path( + project, location + ) + assert expected == actual + + +def test_parse_shared_regional_certificate_authority_path(): + expected = { + "project": "squid", + "location": "clam", + } + path = MemorystoreClient.shared_regional_certificate_authority_path(**expected) + + # Check that the path construction is reversible. + actual = MemorystoreClient.parse_shared_regional_certificate_authority_path(path) + assert expected == actual + + def test_common_billing_account_path(): - billing_account = "oyster" + billing_account = "whelk" expected = "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -4339,7 +4770,7 @@ def test_common_billing_account_path(): def test_parse_common_billing_account_path(): expected = { - "billing_account": "nudibranch", + "billing_account": "octopus", } path = MemorystoreClient.common_billing_account_path(**expected) @@ -4349,7 +4780,7 @@ def test_parse_common_billing_account_path(): def test_common_folder_path(): - folder = "cuttlefish" + folder = "oyster" expected = "folders/{folder}".format( folder=folder, ) @@ -4359,7 +4790,7 @@ def test_common_folder_path(): def test_parse_common_folder_path(): expected = { - "folder": "mussel", + "folder": "nudibranch", } path = MemorystoreClient.common_folder_path(**expected) @@ -4369,7 +4800,7 @@ def test_parse_common_folder_path(): def test_common_organization_path(): - organization = "winkle" + organization = "cuttlefish" expected = "organizations/{organization}".format( organization=organization, ) @@ -4379,7 +4810,7 @@ def test_common_organization_path(): def test_parse_common_organization_path(): expected = { - "organization": "nautilus", + "organization": "mussel", } path = MemorystoreClient.common_organization_path(**expected) @@ -4389,7 +4820,7 @@ def test_parse_common_organization_path(): def test_common_project_path(): - project = "scallop" + project = "winkle" expected = "projects/{project}".format( project=project, ) @@ -4399,7 +4830,7 @@ def test_common_project_path(): def test_parse_common_project_path(): expected = { - "project": "abalone", + "project": "nautilus", } path = MemorystoreClient.common_project_path(**expected) @@ -4409,8 +4840,8 @@ def test_parse_common_project_path(): def test_common_location_path(): - project = "squid" - location = "clam" + project = "scallop" + location = "abalone" expected = "projects/{project}/locations/{location}".format( project=project, location=location, @@ -4421,8 +4852,8 @@ def test_common_location_path(): def test_parse_common_location_path(): expected = { - "project": "whelk", - "location": "octopus", + "project": "squid", + "location": "clam", } path = MemorystoreClient.common_location_path(**expected) diff --git a/packages/google-cloud-pubsub/google/pubsub_v1/types/pubsub.py b/packages/google-cloud-pubsub/google/pubsub_v1/types/pubsub.py index ca4ee51c39f1..7d95585992d6 100644 --- a/packages/google-cloud-pubsub/google/pubsub_v1/types/pubsub.py +++ b/packages/google-cloud-pubsub/google/pubsub_v1/types/pubsub.py @@ -1377,7 +1377,7 @@ class AIInference(proto.Message): that specifies this field must have ``iam.serviceAccounts.actAs`` permission on the service account. If not specified, the Pub/Sub `service - agent <{$universe.dns_names.final_documentation_domain}/iam/docs/service-agents>`__, + agent `__, service-{project_number}@gcp-sa-pubsub.iam.gserviceaccount.com, is used. """ diff --git a/packages/google-cloud-storage/google/cloud/_storage_v2/types/storage.py b/packages/google-cloud-storage/google/cloud/_storage_v2/types/storage.py index 8d326c0936f7..f5678132c6bc 100644 --- a/packages/google-cloud-storage/google/cloud/_storage_v2/types/storage.py +++ b/packages/google-cloud-storage/google/cloud/_storage_v2/types/storage.py @@ -1798,6 +1798,9 @@ class WriteObjectResponse(proto.Message): finalized. This field is a member of `oneof`_ ``write_status``. + persisted_data_checksums (google.cloud._storage_v2.types.ObjectChecksums): + If persisted_size is set, contains checksums of persisted + data. """ persisted_size: int = proto.Field( @@ -1811,6 +1814,11 @@ class WriteObjectResponse(proto.Message): oneof="write_status", message="Object", ) + persisted_data_checksums: "ObjectChecksums" = proto.Field( + proto.MESSAGE, + number=3, + message="ObjectChecksums", + ) class AppendObjectSpec(proto.Message): @@ -1950,8 +1958,9 @@ class BidiWriteObjectRequest(proto.Message): object_checksums (google.cloud._storage_v2.types.ObjectChecksums): Optional. Checksums for the complete object. If the checksums computed by the service don't match the specified - checksums the call fails. Might only be provided in the - first request or the last request (with finish_write set). + checksums the call fails. May be provided in the last + request (with finish_write set). For non-appendable objects + only, may also be provided in the first request. state_lookup (bool): Optional. For each ``BidiWriteObjectRequest`` where ``state_lookup`` is ``true`` or the client closes the @@ -2058,6 +2067,9 @@ class BidiWriteObjectResponse(proto.Message): finalized. This field is a member of `oneof`_ ``write_status``. + persisted_data_checksums (google.cloud._storage_v2.types.ObjectChecksums): + If persisted_size is set, contains checksums of persisted + data. write_handle (google.cloud._storage_v2.types.BidiWriteHandle): An optional write handle that is returned periodically in response messages. Clients @@ -2078,6 +2090,11 @@ class BidiWriteObjectResponse(proto.Message): oneof="write_status", message="Object", ) + persisted_data_checksums: "ObjectChecksums" = proto.Field( + proto.MESSAGE, + number=4, + message="ObjectChecksums", + ) write_handle: "BidiWriteHandle" = proto.Field( proto.MESSAGE, number=3, @@ -2276,6 +2293,9 @@ class QueryWriteStatusResponse(proto.Message): finalized. This field is a member of `oneof`_ ``write_status``. + persisted_data_checksums (google.cloud._storage_v2.types.ObjectChecksums): + If persisted_size is set, contains checksums of persisted + data. """ persisted_size: int = proto.Field( @@ -2289,6 +2309,11 @@ class QueryWriteStatusResponse(proto.Message): oneof="write_status", message="Object", ) + persisted_data_checksums: "ObjectChecksums" = proto.Field( + proto.MESSAGE, + number=3, + message="ObjectChecksums", + ) class RewriteObjectRequest(proto.Message): diff --git a/packages/google-cloud-translate/google/cloud/translate_v3/types/adaptive_mt.py b/packages/google-cloud-translate/google/cloud/translate_v3/types/adaptive_mt.py index d1ffc1cd470f..d849156745ee 100644 --- a/packages/google-cloud-translate/google/cloud/translate_v3/types/adaptive_mt.py +++ b/packages/google-cloud-translate/google/cloud/translate_v3/types/adaptive_mt.py @@ -252,6 +252,8 @@ class AdaptiveMtTranslateRequest(proto.Message): content (MutableSequence[str]): Required. The content of the input in string format. + mime_type (str): + The format of the source text. reference_sentence_config (google.cloud.translate_v3.types.AdaptiveMtTranslateRequest.ReferenceSentenceConfig): Configuration for caller provided reference sentences. @@ -382,6 +384,10 @@ class GlossaryConfig(proto.Message): proto.STRING, number=3, ) + mime_type: str = proto.Field( + proto.STRING, + number=4, + ) reference_sentence_config: ReferenceSentenceConfig = proto.Field( proto.MESSAGE, number=6, diff --git a/packages/google-cloud-translate/tests/unit/gapic/translate_v3/test_translation_service.py b/packages/google-cloud-translate/tests/unit/gapic/translate_v3/test_translation_service.py index 82e3d8518e63..0f5530ca5d6c 100644 --- a/packages/google-cloud-translate/tests/unit/gapic/translate_v3/test_translation_service.py +++ b/packages/google-cloud-translate/tests/unit/gapic/translate_v3/test_translation_service.py @@ -10742,6 +10742,7 @@ def test_adaptive_mt_translate_non_empty_request_with_auto_populated_field(): request = adaptive_mt.AdaptiveMtTranslateRequest( parent="parent_value", dataset="dataset_value", + mime_type="mime_type_value", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -10757,6 +10758,7 @@ def test_adaptive_mt_translate_non_empty_request_with_auto_populated_field(): assert args[0] == adaptive_mt.AdaptiveMtTranslateRequest( parent="parent_value", dataset="dataset_value", + mime_type="mime_type_value", )