diff --git a/librarian.yaml b/librarian.yaml index 4e2390296fe2..ba192d5da155 100644 --- a/librarian.yaml +++ b/librarian.yaml @@ -16,8 +16,8 @@ version: v0.22.0 repo: googleapis/google-cloud-python sources: googleapis: - commit: 73a8001701e1d3a668dbfb72e9ab66c97d107ff6 - sha256: 16b606051acfea9e3d2871a844e1106459294c540c5089fdcf7d306092e27813 + commit: 99f54e6513f09d8df1707a6c553b0a3c6ef9b5fb + sha256: 7cee15fe1ae76a16aaf70425c4380a3a0fcbfeb4ea8e30c934c43f5cd54b9657 default: output: packages tag_format: '{name}-v{version}' diff --git a/packages/google-apps-chat/google/apps/chat/__init__.py b/packages/google-apps-chat/google/apps/chat/__init__.py index 45fb7a15c660..c170d7dd3ff7 100644 --- a/packages/google-apps-chat/google/apps/chat/__init__.py +++ b/packages/google-apps-chat/google/apps/chat/__init__.py @@ -43,6 +43,16 @@ UploadAttachmentRequest, UploadAttachmentResponse, ) +from google.apps.chat_v1.types.availability import ( + Availability, + CustomStatus, + DoNotDisturbMetadata, + GetAvailabilityRequest, + MarkAsActiveRequest, + MarkAsAwayRequest, + MarkAsDoNotDisturbRequest, + UpdateAvailabilityRequest, +) from google.apps.chat_v1.types.contextual_addon import ContextualAddOnMarkup from google.apps.chat_v1.types.deletion_metadata import DeletionMetadata from google.apps.chat_v1.types.event_payload import ( @@ -189,6 +199,14 @@ "GetAttachmentRequest", "UploadAttachmentRequest", "UploadAttachmentResponse", + "Availability", + "CustomStatus", + "DoNotDisturbMetadata", + "GetAvailabilityRequest", + "MarkAsActiveRequest", + "MarkAsAwayRequest", + "MarkAsDoNotDisturbRequest", + "UpdateAvailabilityRequest", "ContextualAddOnMarkup", "DeletionMetadata", "MembershipBatchCreatedEventData", 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 630ee3de1917..1999c88497ba 100644 --- a/packages/google-apps-chat/google/apps/chat_v1/__init__.py +++ b/packages/google-apps-chat/google/apps/chat_v1/__init__.py @@ -45,6 +45,16 @@ UploadAttachmentRequest, UploadAttachmentResponse, ) +from .types.availability import ( + Availability, + CustomStatus, + DoNotDisturbMetadata, + GetAvailabilityRequest, + MarkAsActiveRequest, + MarkAsAwayRequest, + MarkAsDoNotDisturbRequest, + UpdateAvailabilityRequest, +) from .types.contextual_addon import ContextualAddOnMarkup from .types.deletion_metadata import DeletionMetadata from .types.event_payload import ( @@ -261,6 +271,7 @@ def _get_version(dependency_name): "AttachedGif", "Attachment", "AttachmentDataRef", + "Availability", "CalendarEventLinkData", "CardWithId", "ChatServiceClient", @@ -277,6 +288,7 @@ def _get_version(dependency_name): "CreateSpaceRequest", "CustomEmoji", "CustomEmojiMetadata", + "CustomStatus", "DeleteCustomEmojiRequest", "DeleteMembershipRequest", "DeleteMessageRequest", @@ -286,6 +298,7 @@ def _get_version(dependency_name): "DeletionMetadata", "Dialog", "DialogAction", + "DoNotDisturbMetadata", "DriveDataRef", "DriveLinkData", "Emoji", @@ -295,6 +308,7 @@ def _get_version(dependency_name): "FindGroupChatsResponse", "ForwardedMetadata", "GetAttachmentRequest", + "GetAvailabilityRequest", "GetCustomEmojiRequest", "GetMembershipRequest", "GetMessageRequest", @@ -321,6 +335,9 @@ def _get_version(dependency_name): "ListSpaceEventsResponse", "ListSpacesRequest", "ListSpacesResponse", + "MarkAsActiveRequest", + "MarkAsAwayRequest", + "MarkAsDoNotDisturbRequest", "MatchedUrl", "MeetSpaceLinkData", "Membership", @@ -365,6 +382,7 @@ def _get_version(dependency_name): "SpaceView", "Thread", "ThreadReadState", + "UpdateAvailabilityRequest", "UpdateMembershipRequest", "UpdateMessageRequest", "UpdateSectionRequest", 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 974fce08eba2..6f9b1237ca85 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 @@ -90,6 +90,11 @@ "get_attachment" ] }, + "GetAvailability": { + "methods": [ + "get_availability" + ] + }, "GetCustomEmoji": { "methods": [ "get_custom_emoji" @@ -170,6 +175,21 @@ "list_spaces" ] }, + "MarkAsActive": { + "methods": [ + "mark_as_active" + ] + }, + "MarkAsAway": { + "methods": [ + "mark_as_away" + ] + }, + "MarkAsDoNotDisturb": { + "methods": [ + "mark_as_do_not_disturb" + ] + }, "MoveSectionItem": { "methods": [ "move_section_item" @@ -190,6 +210,11 @@ "set_up_space" ] }, + "UpdateAvailability": { + "methods": [ + "update_availability" + ] + }, "UpdateMembership": { "methods": [ "update_membership" @@ -310,6 +335,11 @@ "get_attachment" ] }, + "GetAvailability": { + "methods": [ + "get_availability" + ] + }, "GetCustomEmoji": { "methods": [ "get_custom_emoji" @@ -390,6 +420,21 @@ "list_spaces" ] }, + "MarkAsActive": { + "methods": [ + "mark_as_active" + ] + }, + "MarkAsAway": { + "methods": [ + "mark_as_away" + ] + }, + "MarkAsDoNotDisturb": { + "methods": [ + "mark_as_do_not_disturb" + ] + }, "MoveSectionItem": { "methods": [ "move_section_item" @@ -410,6 +455,11 @@ "set_up_space" ] }, + "UpdateAvailability": { + "methods": [ + "update_availability" + ] + }, "UpdateMembership": { "methods": [ "update_membership" @@ -530,6 +580,11 @@ "get_attachment" ] }, + "GetAvailability": { + "methods": [ + "get_availability" + ] + }, "GetCustomEmoji": { "methods": [ "get_custom_emoji" @@ -610,6 +665,21 @@ "list_spaces" ] }, + "MarkAsActive": { + "methods": [ + "mark_as_active" + ] + }, + "MarkAsAway": { + "methods": [ + "mark_as_away" + ] + }, + "MarkAsDoNotDisturb": { + "methods": [ + "mark_as_do_not_disturb" + ] + }, "MoveSectionItem": { "methods": [ "move_section_item" @@ -630,6 +700,11 @@ "set_up_space" ] }, + "UpdateAvailability": { + "methods": [ + "update_availability" + ] + }, "UpdateMembership": { "methods": [ "update_membership" 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 817b9f7eba50..31f9eac566e1 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 @@ -51,6 +51,7 @@ from google.apps.chat_v1.types import ( annotation, attachment, + availability, contextual_addon, deletion_metadata, event_payload, @@ -70,6 +71,7 @@ thread_read_state, user, ) +from google.apps.chat_v1.types import availability as gc_availability 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 @@ -110,6 +112,8 @@ class ChatServiceAsyncClient: attachment_path = staticmethod(ChatServiceClient.attachment_path) parse_attachment_path = staticmethod(ChatServiceClient.parse_attachment_path) + availability_path = staticmethod(ChatServiceClient.availability_path) + parse_availability_path = staticmethod(ChatServiceClient.parse_availability_path) custom_emoji_path = staticmethod(ChatServiceClient.custom_emoji_path) parse_custom_emoji_path = staticmethod(ChatServiceClient.parse_custom_emoji_path) membership_path = staticmethod(ChatServiceClient.membership_path) @@ -4929,6 +4933,580 @@ async def sample_get_thread_read_state(): # Done; return the response. return response + async def get_availability( + self, + request: Optional[Union[availability.GetAvailabilityRequest, 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]]] = (), + ) -> availability.Availability: + r"""Returns availability information for a human user in Google + Chat. For example, this can be used to check if a user is online + or away, or to retrieve their custom status message. + + This method only retrieves the authenticated user's + availability. + + Requires `user + authentication `__ + with one of the following `authorization + scopes `__: + + - ``https://www.googleapis.com/auth/chat.users.availability.readonly`` + - ``https://www.googleapis.com/auth/chat.users.availability`` + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require 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_get_availability(): + # Create a client + client = chat_v1.ChatServiceAsyncClient() + + # Initialize request argument(s) + request = chat_v1.GetAvailabilityRequest( + name="name_value", + ) + + # Make the request + response = await client.get_availability(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.apps.chat_v1.types.GetAvailabilityRequest, dict]]): + The request object. Request message for the ``GetAvailability`` method. + name (:class:`str`): + Required. The resource name of the availability to + retrieve. + + Format: users/{user}/availability + + ``{user}`` is the id for the Person in the People API or + Admin SDK directory API. For example, + ``users/123456789``. + + The user's email address or ``me`` can also be used as + an alias to refer to the caller. For example, + ``users/user@example.com`` or ``users/me``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.apps.chat_v1.types.Availability: + Represents a user's current + availability information in Google Chat, + including their state (for example, + Active, Away, Do Not Disturb) and any + custom status. + + """ + # Create or coerce a protobuf request 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, availability.GetAvailabilityRequest): + request = availability.GetAvailabilityRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.get_availability + ] + + # 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 mark_as_active( + self, + request: Optional[Union[availability.MarkAsActiveRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> availability.Availability: + r"""Marks user as ``ACTIVE`` in Google Chat. + + Sets the user's availability state to ``ACTIVE``. The ``ACTIVE`` + state lasts until the specified expiration, at which point the + user's state becomes ``AWAY``. Note that if the user is actively + using Chat, the ``ACTIVE`` state duration may extend beyond the + provided expiration. + + This method only updates the authenticated user's availability. + + Requires `user + authentication `__ + with `authorization + scope `__: + + - ``https://www.googleapis.com/auth/chat.users.availability`` + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require 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_mark_as_active(): + # Create a client + client = chat_v1.ChatServiceAsyncClient() + + # Initialize request argument(s) + request = chat_v1.MarkAsActiveRequest( + name="name_value", + ) + + # Make the request + response = await client.mark_as_active(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.apps.chat_v1.types.MarkAsActiveRequest, dict]]): + The request object. Request message for the ``MarkAsActive`` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.apps.chat_v1.types.Availability: + Represents a user's current + availability information in Google Chat, + including their state (for example, + Active, Away, Do Not Disturb) and any + custom status. + + """ + # 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, availability.MarkAsActiveRequest): + request = availability.MarkAsActiveRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.mark_as_active + ] + + # 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 mark_as_away( + self, + request: Optional[Union[availability.MarkAsAwayRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> availability.Availability: + r"""Marks user as ``AWAY`` in Google Chat. + + Sets the user's state to away and is not affected by the user's + activity. + + This method only updates the authenticated user's availability. + + Requires `user + authentication `__ + with `authorization + scope `__: + + - ``https://www.googleapis.com/auth/chat.users.availability`` + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require 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_mark_as_away(): + # Create a client + client = chat_v1.ChatServiceAsyncClient() + + # Initialize request argument(s) + request = chat_v1.MarkAsAwayRequest( + name="name_value", + ) + + # Make the request + response = await client.mark_as_away(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.apps.chat_v1.types.MarkAsAwayRequest, dict]]): + The request object. Request message for the ``MarkAsAway`` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.apps.chat_v1.types.Availability: + Represents a user's current + availability information in Google Chat, + including their state (for example, + Active, Away, Do Not Disturb) and any + custom status. + + """ + # 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, availability.MarkAsAwayRequest): + request = availability.MarkAsAwayRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.mark_as_away + ] + + # 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 mark_as_do_not_disturb( + self, + request: Optional[Union[availability.MarkAsDoNotDisturbRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> availability.Availability: + r"""Marks user as ``DO_NOT_DISTURB`` in Google Chat. + + Sets a user's availability state to ``DO_NOT_DISTURB`` until a + specified expiration time. When in ``DO_NOT_DISTURB``, users + typically won't receive notifications. + + This method only updates the authenticated user's availability. + + Requires `user + authentication `__ + with `authorization + scope `__: + + - ``https://www.googleapis.com/auth/chat.users.availability`` + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require 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_mark_as_do_not_disturb(): + # Create a client + client = chat_v1.ChatServiceAsyncClient() + + # Initialize request argument(s) + request = chat_v1.MarkAsDoNotDisturbRequest( + name="name_value", + ) + + # Make the request + response = await client.mark_as_do_not_disturb(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.apps.chat_v1.types.MarkAsDoNotDisturbRequest, dict]]): + The request object. Request message for the ``MarkAsDoNotDisturb`` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.apps.chat_v1.types.Availability: + Represents a user's current + availability information in Google Chat, + including their state (for example, + Active, Away, Do Not Disturb) and any + custom status. + + """ + # 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, availability.MarkAsDoNotDisturbRequest): + request = availability.MarkAsDoNotDisturbRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.mark_as_do_not_disturb + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def update_availability( + self, + request: Optional[ + Union[gc_availability.UpdateAvailabilityRequest, dict] + ] = None, + *, + availability: Optional[gc_availability.Availability] = 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_availability.Availability: + r"""Updates availability information for a human user. Only the + ``custom_status`` field can be updated through this method. + + This method only updates the authenticated user's availability. + + Requires `user + authentication `__ + with one of the following `authorization + scopes `__: + + - ``https://www.googleapis.com/auth/chat.users.availability`` + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require 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_availability(): + # Create a client + client = chat_v1.ChatServiceAsyncClient() + + # Initialize request argument(s) + request = chat_v1.UpdateAvailabilityRequest( + ) + + # Make the request + response = await client.update_availability(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.apps.chat_v1.types.UpdateAvailabilityRequest, dict]]): + The request object. Request message for the ``UpdateAvailability`` method. + availability (:class:`google.apps.chat_v1.types.Availability`): + Required. The availability to update. + This corresponds to the ``availability`` 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 list of fields to update. The only field + that can be updated is ``custom_status``. + + 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.Availability: + Represents a user's current + availability information in Google Chat, + including their state (for example, + Active, Away, Do Not Disturb) and any + custom status. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [availability, 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_availability.UpdateAvailabilityRequest): + request = gc_availability.UpdateAvailabilityRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if availability is not None: + request.availability = availability + 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_availability + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("availability.name", request.availability.name),) + ), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + async def get_space_event( self, request: Optional[Union[space_event.GetSpaceEventRequest, dict]] = None, 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 cd72936dee09..0c31dcee4e6a 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 @@ -68,6 +68,7 @@ from google.apps.chat_v1.types import ( annotation, attachment, + availability, contextual_addon, deletion_metadata, event_payload, @@ -87,6 +88,7 @@ thread_read_state, user, ) +from google.apps.chat_v1.types import availability as gc_availability 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 @@ -283,6 +285,21 @@ def parse_attachment_path(path: str) -> Dict[str, str]: ) return m.groupdict() if m else {} + @staticmethod + def availability_path( + user: str, + ) -> str: + """Returns a fully-qualified availability string.""" + return "users/{user}/availability".format( + user=user, + ) + + @staticmethod + def parse_availability_path(path: str) -> Dict[str, str]: + """Parses a availability path into its component segments.""" + m = re.match(r"^users/(?P.+?)/availability$", path) + return m.groupdict() if m else {} + @staticmethod def custom_emoji_path( custom_emoji: str, @@ -5492,6 +5509,568 @@ def sample_get_thread_read_state(): # Done; return the response. return response + def get_availability( + self, + request: Optional[Union[availability.GetAvailabilityRequest, 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]]] = (), + ) -> availability.Availability: + r"""Returns availability information for a human user in Google + Chat. For example, this can be used to check if a user is online + or away, or to retrieve their custom status message. + + This method only retrieves the authenticated user's + availability. + + Requires `user + authentication `__ + with one of the following `authorization + scopes `__: + + - ``https://www.googleapis.com/auth/chat.users.availability.readonly`` + - ``https://www.googleapis.com/auth/chat.users.availability`` + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require 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_get_availability(): + # Create a client + client = chat_v1.ChatServiceClient() + + # Initialize request argument(s) + request = chat_v1.GetAvailabilityRequest( + name="name_value", + ) + + # Make the request + response = client.get_availability(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.apps.chat_v1.types.GetAvailabilityRequest, dict]): + The request object. Request message for the ``GetAvailability`` method. + name (str): + Required. The resource name of the availability to + retrieve. + + Format: users/{user}/availability + + ``{user}`` is the id for the Person in the People API or + Admin SDK directory API. For example, + ``users/123456789``. + + The user's email address or ``me`` can also be used as + an alias to refer to the caller. For example, + ``users/user@example.com`` or ``users/me``. + + 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.apps.chat_v1.types.Availability: + Represents a user's current + availability information in Google Chat, + including their state (for example, + Active, Away, Do Not Disturb) and any + custom status. + + """ + # Create or coerce a protobuf request 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, availability.GetAvailabilityRequest): + request = availability.GetAvailabilityRequest(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_availability] + + # 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 mark_as_active( + self, + request: Optional[Union[availability.MarkAsActiveRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> availability.Availability: + r"""Marks user as ``ACTIVE`` in Google Chat. + + Sets the user's availability state to ``ACTIVE``. The ``ACTIVE`` + state lasts until the specified expiration, at which point the + user's state becomes ``AWAY``. Note that if the user is actively + using Chat, the ``ACTIVE`` state duration may extend beyond the + provided expiration. + + This method only updates the authenticated user's availability. + + Requires `user + authentication `__ + with `authorization + scope `__: + + - ``https://www.googleapis.com/auth/chat.users.availability`` + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require 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_mark_as_active(): + # Create a client + client = chat_v1.ChatServiceClient() + + # Initialize request argument(s) + request = chat_v1.MarkAsActiveRequest( + name="name_value", + ) + + # Make the request + response = client.mark_as_active(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.apps.chat_v1.types.MarkAsActiveRequest, dict]): + The request object. Request message for the ``MarkAsActive`` method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.apps.chat_v1.types.Availability: + Represents a user's current + availability information in Google Chat, + including their state (for example, + Active, Away, Do Not Disturb) and any + custom status. + + """ + # 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, availability.MarkAsActiveRequest): + request = availability.MarkAsActiveRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.mark_as_active] + + # 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 mark_as_away( + self, + request: Optional[Union[availability.MarkAsAwayRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> availability.Availability: + r"""Marks user as ``AWAY`` in Google Chat. + + Sets the user's state to away and is not affected by the user's + activity. + + This method only updates the authenticated user's availability. + + Requires `user + authentication `__ + with `authorization + scope `__: + + - ``https://www.googleapis.com/auth/chat.users.availability`` + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require 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_mark_as_away(): + # Create a client + client = chat_v1.ChatServiceClient() + + # Initialize request argument(s) + request = chat_v1.MarkAsAwayRequest( + name="name_value", + ) + + # Make the request + response = client.mark_as_away(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.apps.chat_v1.types.MarkAsAwayRequest, dict]): + The request object. Request message for the ``MarkAsAway`` method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.apps.chat_v1.types.Availability: + Represents a user's current + availability information in Google Chat, + including their state (for example, + Active, Away, Do Not Disturb) and any + custom status. + + """ + # 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, availability.MarkAsAwayRequest): + request = availability.MarkAsAwayRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.mark_as_away] + + # 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 mark_as_do_not_disturb( + self, + request: Optional[Union[availability.MarkAsDoNotDisturbRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> availability.Availability: + r"""Marks user as ``DO_NOT_DISTURB`` in Google Chat. + + Sets a user's availability state to ``DO_NOT_DISTURB`` until a + specified expiration time. When in ``DO_NOT_DISTURB``, users + typically won't receive notifications. + + This method only updates the authenticated user's availability. + + Requires `user + authentication `__ + with `authorization + scope `__: + + - ``https://www.googleapis.com/auth/chat.users.availability`` + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require 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_mark_as_do_not_disturb(): + # Create a client + client = chat_v1.ChatServiceClient() + + # Initialize request argument(s) + request = chat_v1.MarkAsDoNotDisturbRequest( + name="name_value", + ) + + # Make the request + response = client.mark_as_do_not_disturb(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.apps.chat_v1.types.MarkAsDoNotDisturbRequest, dict]): + The request object. Request message for the ``MarkAsDoNotDisturb`` method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.apps.chat_v1.types.Availability: + Represents a user's current + availability information in Google Chat, + including their state (for example, + Active, Away, Do Not Disturb) and any + custom status. + + """ + # 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, availability.MarkAsDoNotDisturbRequest): + request = availability.MarkAsDoNotDisturbRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.mark_as_do_not_disturb] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def update_availability( + self, + request: Optional[ + Union[gc_availability.UpdateAvailabilityRequest, dict] + ] = None, + *, + availability: Optional[gc_availability.Availability] = 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_availability.Availability: + r"""Updates availability information for a human user. Only the + ``custom_status`` field can be updated through this method. + + This method only updates the authenticated user's availability. + + Requires `user + authentication `__ + with one of the following `authorization + scopes `__: + + - ``https://www.googleapis.com/auth/chat.users.availability`` + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require 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_availability(): + # Create a client + client = chat_v1.ChatServiceClient() + + # Initialize request argument(s) + request = chat_v1.UpdateAvailabilityRequest( + ) + + # Make the request + response = client.update_availability(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.apps.chat_v1.types.UpdateAvailabilityRequest, dict]): + The request object. Request message for the ``UpdateAvailability`` method. + availability (google.apps.chat_v1.types.Availability): + Required. The availability to update. + This corresponds to the ``availability`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. The list of fields to update. The only field + that can be updated is ``custom_status``. + + 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.Availability: + Represents a user's current + availability information in Google Chat, + including their state (for example, + Active, Away, Do Not Disturb) and any + custom status. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [availability, 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_availability.UpdateAvailabilityRequest): + request = gc_availability.UpdateAvailabilityRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if availability is not None: + request.availability = availability + 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_availability] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("availability.name", request.availability.name),) + ), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + def get_space_event( self, request: Optional[Union[space_event.GetSpaceEventRequest, dict]] = None, 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 b4230c8d86cd..532795b4a00e 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 @@ -29,6 +29,7 @@ from google.apps.chat_v1 import gapic_version as package_version from google.apps.chat_v1.types import ( attachment, + availability, membership, message, reaction, @@ -40,6 +41,7 @@ space_setup, thread_read_state, ) +from google.apps.chat_v1.types import availability as gc_availability 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 @@ -91,6 +93,8 @@ class ChatServiceTransport(abc.ABC): "https://www.googleapis.com/auth/chat.spaces", "https://www.googleapis.com/auth/chat.spaces.create", "https://www.googleapis.com/auth/chat.spaces.readonly", + "https://www.googleapis.com/auth/chat.users.availability", + "https://www.googleapis.com/auth/chat.users.availability.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", @@ -647,6 +651,76 @@ def _prep_wrapped_messages(self, client_info): default_timeout=30.0, client_info=client_info, ), + self.get_availability: gapic_v1.method.wrap_method( + self.get_availability, + 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.mark_as_active: gapic_v1.method.wrap_method( + self.mark_as_active, + 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.mark_as_away: gapic_v1.method.wrap_method( + self.mark_as_away, + 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.mark_as_do_not_disturb: gapic_v1.method.wrap_method( + self.mark_as_do_not_disturb, + 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_availability: gapic_v1.method.wrap_method( + self.update_availability, + 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.get_space_event: gapic_v1.method.wrap_method( self.get_space_event, default_retry=retries.Retry( @@ -1113,6 +1187,51 @@ def get_thread_read_state( ]: raise NotImplementedError() + @property + def get_availability( + self, + ) -> Callable[ + [availability.GetAvailabilityRequest], + Union[availability.Availability, Awaitable[availability.Availability]], + ]: + raise NotImplementedError() + + @property + def mark_as_active( + self, + ) -> Callable[ + [availability.MarkAsActiveRequest], + Union[availability.Availability, Awaitable[availability.Availability]], + ]: + raise NotImplementedError() + + @property + def mark_as_away( + self, + ) -> Callable[ + [availability.MarkAsAwayRequest], + Union[availability.Availability, Awaitable[availability.Availability]], + ]: + raise NotImplementedError() + + @property + def mark_as_do_not_disturb( + self, + ) -> Callable[ + [availability.MarkAsDoNotDisturbRequest], + Union[availability.Availability, Awaitable[availability.Availability]], + ]: + raise NotImplementedError() + + @property + def update_availability( + self, + ) -> Callable[ + [gc_availability.UpdateAvailabilityRequest], + Union[gc_availability.Availability, Awaitable[gc_availability.Availability]], + ]: + raise NotImplementedError() + @property def get_space_event( self, 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 7dcb48752050..4a4501e6f9c7 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 @@ -31,6 +31,7 @@ from google.apps.chat_v1.types import ( attachment, + availability, membership, message, reaction, @@ -42,6 +43,7 @@ space_setup, thread_read_state, ) +from google.apps.chat_v1.types import availability as gc_availability 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 @@ -1995,6 +1997,201 @@ def get_thread_read_state( ) return self._stubs["get_thread_read_state"] + @property + def get_availability( + self, + ) -> Callable[[availability.GetAvailabilityRequest], availability.Availability]: + r"""Return a callable for the get availability method over gRPC. + + Returns availability information for a human user in Google + Chat. For example, this can be used to check if a user is online + or away, or to retrieve their custom status message. + + This method only retrieves the authenticated user's + availability. + + Requires `user + authentication `__ + with one of the following `authorization + scopes `__: + + - ``https://www.googleapis.com/auth/chat.users.availability.readonly`` + - ``https://www.googleapis.com/auth/chat.users.availability`` + + Returns: + Callable[[~.GetAvailabilityRequest], + ~.Availability]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_availability" not in self._stubs: + self._stubs["get_availability"] = self._logged_channel.unary_unary( + "/google.chat.v1.ChatService/GetAvailability", + request_serializer=availability.GetAvailabilityRequest.serialize, + response_deserializer=availability.Availability.deserialize, + ) + return self._stubs["get_availability"] + + @property + def mark_as_active( + self, + ) -> Callable[[availability.MarkAsActiveRequest], availability.Availability]: + r"""Return a callable for the mark as active method over gRPC. + + Marks user as ``ACTIVE`` in Google Chat. + + Sets the user's availability state to ``ACTIVE``. The ``ACTIVE`` + state lasts until the specified expiration, at which point the + user's state becomes ``AWAY``. Note that if the user is actively + using Chat, the ``ACTIVE`` state duration may extend beyond the + provided expiration. + + This method only updates the authenticated user's availability. + + Requires `user + authentication `__ + with `authorization + scope `__: + + - ``https://www.googleapis.com/auth/chat.users.availability`` + + Returns: + Callable[[~.MarkAsActiveRequest], + ~.Availability]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "mark_as_active" not in self._stubs: + self._stubs["mark_as_active"] = self._logged_channel.unary_unary( + "/google.chat.v1.ChatService/MarkAsActive", + request_serializer=availability.MarkAsActiveRequest.serialize, + response_deserializer=availability.Availability.deserialize, + ) + return self._stubs["mark_as_active"] + + @property + def mark_as_away( + self, + ) -> Callable[[availability.MarkAsAwayRequest], availability.Availability]: + r"""Return a callable for the mark as away method over gRPC. + + Marks user as ``AWAY`` in Google Chat. + + Sets the user's state to away and is not affected by the user's + activity. + + This method only updates the authenticated user's availability. + + Requires `user + authentication `__ + with `authorization + scope `__: + + - ``https://www.googleapis.com/auth/chat.users.availability`` + + Returns: + Callable[[~.MarkAsAwayRequest], + ~.Availability]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "mark_as_away" not in self._stubs: + self._stubs["mark_as_away"] = self._logged_channel.unary_unary( + "/google.chat.v1.ChatService/MarkAsAway", + request_serializer=availability.MarkAsAwayRequest.serialize, + response_deserializer=availability.Availability.deserialize, + ) + return self._stubs["mark_as_away"] + + @property + def mark_as_do_not_disturb( + self, + ) -> Callable[[availability.MarkAsDoNotDisturbRequest], availability.Availability]: + r"""Return a callable for the mark as do not disturb method over gRPC. + + Marks user as ``DO_NOT_DISTURB`` in Google Chat. + + Sets a user's availability state to ``DO_NOT_DISTURB`` until a + specified expiration time. When in ``DO_NOT_DISTURB``, users + typically won't receive notifications. + + This method only updates the authenticated user's availability. + + Requires `user + authentication `__ + with `authorization + scope `__: + + - ``https://www.googleapis.com/auth/chat.users.availability`` + + Returns: + Callable[[~.MarkAsDoNotDisturbRequest], + ~.Availability]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "mark_as_do_not_disturb" not in self._stubs: + self._stubs["mark_as_do_not_disturb"] = self._logged_channel.unary_unary( + "/google.chat.v1.ChatService/MarkAsDoNotDisturb", + request_serializer=availability.MarkAsDoNotDisturbRequest.serialize, + response_deserializer=availability.Availability.deserialize, + ) + return self._stubs["mark_as_do_not_disturb"] + + @property + def update_availability( + self, + ) -> Callable[ + [gc_availability.UpdateAvailabilityRequest], gc_availability.Availability + ]: + r"""Return a callable for the update availability method over gRPC. + + Updates availability information for a human user. Only the + ``custom_status`` field can be updated through this method. + + This method only updates the authenticated user's availability. + + Requires `user + authentication `__ + with one of the following `authorization + scopes `__: + + - ``https://www.googleapis.com/auth/chat.users.availability`` + + Returns: + Callable[[~.UpdateAvailabilityRequest], + ~.Availability]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_availability" not in self._stubs: + self._stubs["update_availability"] = self._logged_channel.unary_unary( + "/google.chat.v1.ChatService/UpdateAvailability", + request_serializer=gc_availability.UpdateAvailabilityRequest.serialize, + response_deserializer=gc_availability.Availability.deserialize, + ) + return self._stubs["update_availability"] + @property def get_space_event( self, 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 33ac93647828..a32f2688e4e8 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 @@ -34,6 +34,7 @@ from google.apps.chat_v1.types import ( attachment, + availability, membership, message, reaction, @@ -45,6 +46,7 @@ space_setup, thread_read_state, ) +from google.apps.chat_v1.types import availability as gc_availability 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 @@ -2029,6 +2031,210 @@ def get_thread_read_state( ) return self._stubs["get_thread_read_state"] + @property + def get_availability( + self, + ) -> Callable[ + [availability.GetAvailabilityRequest], Awaitable[availability.Availability] + ]: + r"""Return a callable for the get availability method over gRPC. + + Returns availability information for a human user in Google + Chat. For example, this can be used to check if a user is online + or away, or to retrieve their custom status message. + + This method only retrieves the authenticated user's + availability. + + Requires `user + authentication `__ + with one of the following `authorization + scopes `__: + + - ``https://www.googleapis.com/auth/chat.users.availability.readonly`` + - ``https://www.googleapis.com/auth/chat.users.availability`` + + Returns: + Callable[[~.GetAvailabilityRequest], + Awaitable[~.Availability]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_availability" not in self._stubs: + self._stubs["get_availability"] = self._logged_channel.unary_unary( + "/google.chat.v1.ChatService/GetAvailability", + request_serializer=availability.GetAvailabilityRequest.serialize, + response_deserializer=availability.Availability.deserialize, + ) + return self._stubs["get_availability"] + + @property + def mark_as_active( + self, + ) -> Callable[ + [availability.MarkAsActiveRequest], Awaitable[availability.Availability] + ]: + r"""Return a callable for the mark as active method over gRPC. + + Marks user as ``ACTIVE`` in Google Chat. + + Sets the user's availability state to ``ACTIVE``. The ``ACTIVE`` + state lasts until the specified expiration, at which point the + user's state becomes ``AWAY``. Note that if the user is actively + using Chat, the ``ACTIVE`` state duration may extend beyond the + provided expiration. + + This method only updates the authenticated user's availability. + + Requires `user + authentication `__ + with `authorization + scope `__: + + - ``https://www.googleapis.com/auth/chat.users.availability`` + + Returns: + Callable[[~.MarkAsActiveRequest], + Awaitable[~.Availability]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "mark_as_active" not in self._stubs: + self._stubs["mark_as_active"] = self._logged_channel.unary_unary( + "/google.chat.v1.ChatService/MarkAsActive", + request_serializer=availability.MarkAsActiveRequest.serialize, + response_deserializer=availability.Availability.deserialize, + ) + return self._stubs["mark_as_active"] + + @property + def mark_as_away( + self, + ) -> Callable[ + [availability.MarkAsAwayRequest], Awaitable[availability.Availability] + ]: + r"""Return a callable for the mark as away method over gRPC. + + Marks user as ``AWAY`` in Google Chat. + + Sets the user's state to away and is not affected by the user's + activity. + + This method only updates the authenticated user's availability. + + Requires `user + authentication `__ + with `authorization + scope `__: + + - ``https://www.googleapis.com/auth/chat.users.availability`` + + Returns: + Callable[[~.MarkAsAwayRequest], + Awaitable[~.Availability]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "mark_as_away" not in self._stubs: + self._stubs["mark_as_away"] = self._logged_channel.unary_unary( + "/google.chat.v1.ChatService/MarkAsAway", + request_serializer=availability.MarkAsAwayRequest.serialize, + response_deserializer=availability.Availability.deserialize, + ) + return self._stubs["mark_as_away"] + + @property + def mark_as_do_not_disturb( + self, + ) -> Callable[ + [availability.MarkAsDoNotDisturbRequest], Awaitable[availability.Availability] + ]: + r"""Return a callable for the mark as do not disturb method over gRPC. + + Marks user as ``DO_NOT_DISTURB`` in Google Chat. + + Sets a user's availability state to ``DO_NOT_DISTURB`` until a + specified expiration time. When in ``DO_NOT_DISTURB``, users + typically won't receive notifications. + + This method only updates the authenticated user's availability. + + Requires `user + authentication `__ + with `authorization + scope `__: + + - ``https://www.googleapis.com/auth/chat.users.availability`` + + Returns: + Callable[[~.MarkAsDoNotDisturbRequest], + Awaitable[~.Availability]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "mark_as_do_not_disturb" not in self._stubs: + self._stubs["mark_as_do_not_disturb"] = self._logged_channel.unary_unary( + "/google.chat.v1.ChatService/MarkAsDoNotDisturb", + request_serializer=availability.MarkAsDoNotDisturbRequest.serialize, + response_deserializer=availability.Availability.deserialize, + ) + return self._stubs["mark_as_do_not_disturb"] + + @property + def update_availability( + self, + ) -> Callable[ + [gc_availability.UpdateAvailabilityRequest], + Awaitable[gc_availability.Availability], + ]: + r"""Return a callable for the update availability method over gRPC. + + Updates availability information for a human user. Only the + ``custom_status`` field can be updated through this method. + + This method only updates the authenticated user's availability. + + Requires `user + authentication `__ + with one of the following `authorization + scopes `__: + + - ``https://www.googleapis.com/auth/chat.users.availability`` + + Returns: + Callable[[~.UpdateAvailabilityRequest], + Awaitable[~.Availability]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_availability" not in self._stubs: + self._stubs["update_availability"] = self._logged_channel.unary_unary( + "/google.chat.v1.ChatService/UpdateAvailability", + request_serializer=gc_availability.UpdateAvailabilityRequest.serialize, + response_deserializer=gc_availability.Availability.deserialize, + ) + return self._stubs["update_availability"] + @property def get_space_event( self, @@ -2977,6 +3183,76 @@ def _prep_wrapped_messages(self, client_info): default_timeout=30.0, client_info=client_info, ), + self.get_availability: self._wrap_method( + self.get_availability, + 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.mark_as_active: self._wrap_method( + self.mark_as_active, + 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.mark_as_away: self._wrap_method( + self.mark_as_away, + 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.mark_as_do_not_disturb: self._wrap_method( + self.mark_as_do_not_disturb, + 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_availability: self._wrap_method( + self.update_availability, + 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.get_space_event: self._wrap_method( self.get_space_event, default_retry=retries.AsyncRetry( 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 7cbcd89e7427..24bed9b4ec28 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 @@ -31,6 +31,7 @@ from google.apps.chat_v1.types import ( attachment, + availability, membership, message, reaction, @@ -42,6 +43,7 @@ space_setup, thread_read_state, ) +from google.apps.chat_v1.types import availability as gc_availability 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 @@ -202,6 +204,14 @@ def post_get_attachment(self, response): logging.log(f"Received response: {response}") return response + def pre_get_availability(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_availability(self, response): + logging.log(f"Received response: {response}") + return response + def pre_get_custom_emoji(self, request, metadata): logging.log(f"Received request: {request}") return request, metadata @@ -330,6 +340,30 @@ def post_list_spaces(self, response): logging.log(f"Received response: {response}") return response + def pre_mark_as_active(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_mark_as_active(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_mark_as_away(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_mark_as_away(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_mark_as_do_not_disturb(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_mark_as_do_not_disturb(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 @@ -362,6 +396,14 @@ def post_set_up_space(self, response): logging.log(f"Received response: {response}") return response + def pre_update_availability(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_availability(self, response): + logging.log(f"Received response: {response}") + return response + def pre_update_membership(self, request, metadata): logging.log(f"Received request: {request}") return request, metadata @@ -1000,6 +1042,54 @@ def post_get_attachment_with_metadata( """ return response, metadata + def pre_get_availability( + self, + request: availability.GetAvailabilityRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + availability.GetAvailabilityRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for get_availability + + Override in a subclass to manipulate the request or metadata + before they are sent to the ChatService server. + """ + return request, metadata + + def post_get_availability( + self, response: availability.Availability + ) -> availability.Availability: + """Post-rpc interceptor for get_availability + + DEPRECATED. Please use the `post_get_availability_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_get_availability` interceptor runs + before the `post_get_availability_with_metadata` interceptor. + """ + return response + + def post_get_availability_with_metadata( + self, + response: availability.Availability, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[availability.Availability, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for get_availability + + 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_get_availability_with_metadata` + interceptor in new development instead of the `post_get_availability` interceptor. + When both interceptors are used, this `post_get_availability_with_metadata` interceptor runs after the + `post_get_availability` interceptor. The (possibly modified) response returned by + `post_get_availability` will be passed to + `post_get_availability_with_metadata`. + """ + return response, metadata + def pre_get_custom_emoji( self, request: reaction.GetCustomEmojiRequest, @@ -1766,6 +1856,148 @@ def post_list_spaces_with_metadata( """ return response, metadata + def pre_mark_as_active( + self, + request: availability.MarkAsActiveRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + availability.MarkAsActiveRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for mark_as_active + + Override in a subclass to manipulate the request or metadata + before they are sent to the ChatService server. + """ + return request, metadata + + def post_mark_as_active( + self, response: availability.Availability + ) -> availability.Availability: + """Post-rpc interceptor for mark_as_active + + DEPRECATED. Please use the `post_mark_as_active_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_mark_as_active` interceptor runs + before the `post_mark_as_active_with_metadata` interceptor. + """ + return response + + def post_mark_as_active_with_metadata( + self, + response: availability.Availability, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[availability.Availability, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for mark_as_active + + 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_mark_as_active_with_metadata` + interceptor in new development instead of the `post_mark_as_active` interceptor. + When both interceptors are used, this `post_mark_as_active_with_metadata` interceptor runs after the + `post_mark_as_active` interceptor. The (possibly modified) response returned by + `post_mark_as_active` will be passed to + `post_mark_as_active_with_metadata`. + """ + return response, metadata + + def pre_mark_as_away( + self, + request: availability.MarkAsAwayRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[availability.MarkAsAwayRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for mark_as_away + + Override in a subclass to manipulate the request or metadata + before they are sent to the ChatService server. + """ + return request, metadata + + def post_mark_as_away( + self, response: availability.Availability + ) -> availability.Availability: + """Post-rpc interceptor for mark_as_away + + DEPRECATED. Please use the `post_mark_as_away_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_mark_as_away` interceptor runs + before the `post_mark_as_away_with_metadata` interceptor. + """ + return response + + def post_mark_as_away_with_metadata( + self, + response: availability.Availability, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[availability.Availability, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for mark_as_away + + 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_mark_as_away_with_metadata` + interceptor in new development instead of the `post_mark_as_away` interceptor. + When both interceptors are used, this `post_mark_as_away_with_metadata` interceptor runs after the + `post_mark_as_away` interceptor. The (possibly modified) response returned by + `post_mark_as_away` will be passed to + `post_mark_as_away_with_metadata`. + """ + return response, metadata + + def pre_mark_as_do_not_disturb( + self, + request: availability.MarkAsDoNotDisturbRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + availability.MarkAsDoNotDisturbRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for mark_as_do_not_disturb + + Override in a subclass to manipulate the request or metadata + before they are sent to the ChatService server. + """ + return request, metadata + + def post_mark_as_do_not_disturb( + self, response: availability.Availability + ) -> availability.Availability: + """Post-rpc interceptor for mark_as_do_not_disturb + + DEPRECATED. Please use the `post_mark_as_do_not_disturb_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_mark_as_do_not_disturb` interceptor runs + before the `post_mark_as_do_not_disturb_with_metadata` interceptor. + """ + return response + + def post_mark_as_do_not_disturb_with_metadata( + self, + response: availability.Availability, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[availability.Availability, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for mark_as_do_not_disturb + + 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_mark_as_do_not_disturb_with_metadata` + interceptor in new development instead of the `post_mark_as_do_not_disturb` interceptor. + When both interceptors are used, this `post_mark_as_do_not_disturb_with_metadata` interceptor runs after the + `post_mark_as_do_not_disturb` interceptor. The (possibly modified) response returned by + `post_mark_as_do_not_disturb` will be passed to + `post_mark_as_do_not_disturb_with_metadata`. + """ + return response, metadata + def pre_move_section_item( self, request: section.MoveSectionItemRequest, @@ -1950,6 +2182,55 @@ def post_set_up_space_with_metadata( """ return response, metadata + def pre_update_availability( + self, + request: gc_availability.UpdateAvailabilityRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + gc_availability.UpdateAvailabilityRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for update_availability + + Override in a subclass to manipulate the request or metadata + before they are sent to the ChatService server. + """ + return request, metadata + + def post_update_availability( + self, response: gc_availability.Availability + ) -> gc_availability.Availability: + """Post-rpc interceptor for update_availability + + DEPRECATED. Please use the `post_update_availability_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_availability` interceptor runs + before the `post_update_availability_with_metadata` interceptor. + """ + return response + + def post_update_availability_with_metadata( + self, + response: gc_availability.Availability, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[gc_availability.Availability, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for update_availability + + 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_availability_with_metadata` + interceptor in new development instead of the `post_update_availability` interceptor. + When both interceptors are used, this `post_update_availability_with_metadata` interceptor runs after the + `post_update_availability` interceptor. The (possibly modified) response returned by + `post_update_availability` will be passed to + `post_update_availability_with_metadata`. + """ + return response, metadata + def pre_update_membership( self, request: gc_membership.UpdateMembershipRequest, @@ -4627,11 +4908,11 @@ def __call__( ) return resp - class _GetCustomEmoji( - _BaseChatServiceRestTransport._BaseGetCustomEmoji, ChatServiceRestStub + class _GetAvailability( + _BaseChatServiceRestTransport._BaseGetAvailability, ChatServiceRestStub ): def __hash__(self): - return hash("ChatServiceRestTransport.GetCustomEmoji") + return hash("ChatServiceRestTransport.GetAvailability") @staticmethod def _get_response( @@ -4657,18 +4938,17 @@ def _get_response( def __call__( self, - request: reaction.GetCustomEmojiRequest, + request: availability.GetAvailabilityRequest, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> reaction.CustomEmoji: - r"""Call the get custom emoji method over HTTP. + ) -> availability.Availability: + r"""Call the get availability method over HTTP. Args: - request (~.reaction.GetCustomEmojiRequest): - The request object. A request to return a single custom - emoji. + request (~.availability.GetAvailabilityRequest): + The request object. Request message for the ``GetAvailability`` method. retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -4678,25 +4958,28 @@ def __call__( be of type `bytes`. Returns: - ~.reaction.CustomEmoji: - Represents a `custom - emoji `__. + ~.availability.Availability: + Represents a user's current + availability information in Google Chat, + including their state (for example, + Active, Away, Do Not Disturb) and any + custom status. """ http_options = ( - _BaseChatServiceRestTransport._BaseGetCustomEmoji._get_http_options() + _BaseChatServiceRestTransport._BaseGetAvailability._get_http_options() ) - request, metadata = self._interceptor.pre_get_custom_emoji( + request, metadata = self._interceptor.pre_get_availability( request, metadata ) - transcoded_request = _BaseChatServiceRestTransport._BaseGetCustomEmoji._get_transcoded_request( + transcoded_request = _BaseChatServiceRestTransport._BaseGetAvailability._get_transcoded_request( http_options, request ) # Jsonify the query params - query_params = _BaseChatServiceRestTransport._BaseGetCustomEmoji._get_query_params_json( + query_params = _BaseChatServiceRestTransport._BaseGetAvailability._get_query_params_json( transcoded_request ) @@ -4718,17 +5001,17 @@ def __call__( "headers": dict(metadata), } _LOGGER.debug( - f"Sending request for google.chat_v1.ChatServiceClient.GetCustomEmoji", + f"Sending request for google.chat_v1.ChatServiceClient.GetAvailability", extra={ "serviceName": "google.chat.v1.ChatService", - "rpcName": "GetCustomEmoji", + "rpcName": "GetAvailability", "httpRequest": http_request, "metadata": http_request["headers"], }, ) # Send the request - response = ChatServiceRestTransport._GetCustomEmoji._get_response( + response = ChatServiceRestTransport._GetAvailability._get_response( self._host, metadata, query_params, @@ -4743,21 +5026,21 @@ def __call__( raise core_exceptions.from_http_response(response) # Return the response - resp = reaction.CustomEmoji() - pb_resp = reaction.CustomEmoji.pb(resp) + resp = availability.Availability() + pb_resp = availability.Availability.pb(resp) json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_get_custom_emoji(resp) + resp = self._interceptor.post_get_availability(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_get_custom_emoji_with_metadata( + resp, _ = self._interceptor.post_get_availability_with_metadata( resp, response_metadata ) if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( logging.DEBUG ): # pragma: NO COVER try: - response_payload = reaction.CustomEmoji.to_json(response) + response_payload = availability.Availability.to_json(response) except: response_payload = None http_response = { @@ -4766,21 +5049,21 @@ def __call__( "status": response.status_code, } _LOGGER.debug( - "Received response for google.chat_v1.ChatServiceClient.get_custom_emoji", + "Received response for google.chat_v1.ChatServiceClient.get_availability", extra={ "serviceName": "google.chat.v1.ChatService", - "rpcName": "GetCustomEmoji", + "rpcName": "GetAvailability", "metadata": http_response["headers"], "httpResponse": http_response, }, ) return resp - class _GetMembership( - _BaseChatServiceRestTransport._BaseGetMembership, ChatServiceRestStub + class _GetCustomEmoji( + _BaseChatServiceRestTransport._BaseGetCustomEmoji, ChatServiceRestStub ): def __hash__(self): - return hash("ChatServiceRestTransport.GetMembership") + return hash("ChatServiceRestTransport.GetCustomEmoji") @staticmethod def _get_response( @@ -4806,18 +5089,18 @@ def _get_response( def __call__( self, - request: membership.GetMembershipRequest, + request: reaction.GetCustomEmojiRequest, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> membership.Membership: - r"""Call the get membership method over HTTP. + ) -> reaction.CustomEmoji: + r"""Call the get custom emoji method over HTTP. Args: - request (~.membership.GetMembershipRequest): - The request object. Request to get a membership of a - space. + request (~.reaction.GetCustomEmojiRequest): + The request object. A request to return a single custom + emoji. retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -4827,28 +5110,26 @@ def __call__( be of type `bytes`. Returns: - ~.membership.Membership: - Represents a membership relation in - Google Chat, such as whether a user or - Chat app is invited to, part of, or - absent from a space. + ~.reaction.CustomEmoji: + Represents a `custom + emoji `__. """ http_options = ( - _BaseChatServiceRestTransport._BaseGetMembership._get_http_options() + _BaseChatServiceRestTransport._BaseGetCustomEmoji._get_http_options() ) - request, metadata = self._interceptor.pre_get_membership(request, metadata) - transcoded_request = _BaseChatServiceRestTransport._BaseGetMembership._get_transcoded_request( + request, metadata = self._interceptor.pre_get_custom_emoji( + request, metadata + ) + transcoded_request = _BaseChatServiceRestTransport._BaseGetCustomEmoji._get_transcoded_request( http_options, request ) # Jsonify the query params - query_params = ( - _BaseChatServiceRestTransport._BaseGetMembership._get_query_params_json( - transcoded_request - ) + query_params = _BaseChatServiceRestTransport._BaseGetCustomEmoji._get_query_params_json( + transcoded_request ) if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( @@ -4869,17 +5150,17 @@ def __call__( "headers": dict(metadata), } _LOGGER.debug( - f"Sending request for google.chat_v1.ChatServiceClient.GetMembership", + f"Sending request for google.chat_v1.ChatServiceClient.GetCustomEmoji", extra={ "serviceName": "google.chat.v1.ChatService", - "rpcName": "GetMembership", + "rpcName": "GetCustomEmoji", "httpRequest": http_request, "metadata": http_request["headers"], }, ) # Send the request - response = ChatServiceRestTransport._GetMembership._get_response( + response = ChatServiceRestTransport._GetCustomEmoji._get_response( self._host, metadata, query_params, @@ -4894,21 +5175,21 @@ def __call__( raise core_exceptions.from_http_response(response) # Return the response - resp = membership.Membership() - pb_resp = membership.Membership.pb(resp) + resp = reaction.CustomEmoji() + pb_resp = reaction.CustomEmoji.pb(resp) json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_get_membership(resp) + resp = self._interceptor.post_get_custom_emoji(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_get_membership_with_metadata( + resp, _ = self._interceptor.post_get_custom_emoji_with_metadata( resp, response_metadata ) if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( logging.DEBUG ): # pragma: NO COVER try: - response_payload = membership.Membership.to_json(response) + response_payload = reaction.CustomEmoji.to_json(response) except: response_payload = None http_response = { @@ -4917,21 +5198,172 @@ def __call__( "status": response.status_code, } _LOGGER.debug( - "Received response for google.chat_v1.ChatServiceClient.get_membership", + "Received response for google.chat_v1.ChatServiceClient.get_custom_emoji", extra={ "serviceName": "google.chat.v1.ChatService", - "rpcName": "GetMembership", + "rpcName": "GetCustomEmoji", "metadata": http_response["headers"], "httpResponse": http_response, }, ) return resp - class _GetMessage( - _BaseChatServiceRestTransport._BaseGetMessage, ChatServiceRestStub + class _GetMembership( + _BaseChatServiceRestTransport._BaseGetMembership, ChatServiceRestStub ): def __hash__(self): - return hash("ChatServiceRestTransport.GetMessage") + return hash("ChatServiceRestTransport.GetMembership") + + @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: membership.GetMembershipRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> membership.Membership: + r"""Call the get membership method over HTTP. + + Args: + request (~.membership.GetMembershipRequest): + The request object. Request to get a membership of a + space. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.membership.Membership: + Represents a membership relation in + Google Chat, such as whether a user or + Chat app is invited to, part of, or + absent from a space. + + """ + + http_options = ( + _BaseChatServiceRestTransport._BaseGetMembership._get_http_options() + ) + + request, metadata = self._interceptor.pre_get_membership(request, metadata) + transcoded_request = _BaseChatServiceRestTransport._BaseGetMembership._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = ( + _BaseChatServiceRestTransport._BaseGetMembership._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.GetMembership", + extra={ + "serviceName": "google.chat.v1.ChatService", + "rpcName": "GetMembership", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = ChatServiceRestTransport._GetMembership._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 = membership.Membership() + pb_resp = membership.Membership.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_get_membership(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_get_membership_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = membership.Membership.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.get_membership", + extra={ + "serviceName": "google.chat.v1.ChatService", + "rpcName": "GetMembership", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _GetMessage( + _BaseChatServiceRestTransport._BaseGetMessage, ChatServiceRestStub + ): + def __hash__(self): + return hash("ChatServiceRestTransport.GetMessage") @staticmethod def _get_response( @@ -7035,11 +7467,11 @@ def __call__( ) return resp - class _MoveSectionItem( - _BaseChatServiceRestTransport._BaseMoveSectionItem, ChatServiceRestStub + class _MarkAsActive( + _BaseChatServiceRestTransport._BaseMarkAsActive, ChatServiceRestStub ): def __hash__(self): - return hash("ChatServiceRestTransport.MoveSectionItem") + return hash("ChatServiceRestTransport.MarkAsActive") @staticmethod def _get_response( @@ -7066,18 +7498,17 @@ def _get_response( def __call__( self, - request: section.MoveSectionItemRequest, + request: availability.MarkAsActiveRequest, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> section.MoveSectionItemResponse: - r"""Call the move section item method over HTTP. + ) -> availability.Availability: + r"""Call the mark as active method over HTTP. Args: - request (~.section.MoveSectionItemRequest): - The request object. Request message for moving a section - item across sections. + request (~.availability.MarkAsActiveRequest): + The request object. Request message for the ``MarkAsActive`` method. retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -7087,30 +7518,37 @@ def __call__( be of type `bytes`. Returns: - ~.section.MoveSectionItemResponse: - Response message for moving a section - item. + ~.availability.Availability: + Represents a user's current + availability information in Google Chat, + including their state (for example, + Active, Away, Do Not Disturb) and any + custom status. """ http_options = ( - _BaseChatServiceRestTransport._BaseMoveSectionItem._get_http_options() + _BaseChatServiceRestTransport._BaseMarkAsActive._get_http_options() ) - request, metadata = self._interceptor.pre_move_section_item( - request, metadata - ) - transcoded_request = _BaseChatServiceRestTransport._BaseMoveSectionItem._get_transcoded_request( - http_options, request + request, metadata = self._interceptor.pre_mark_as_active(request, metadata) + transcoded_request = ( + _BaseChatServiceRestTransport._BaseMarkAsActive._get_transcoded_request( + http_options, request + ) ) - body = _BaseChatServiceRestTransport._BaseMoveSectionItem._get_request_body_json( - transcoded_request + body = ( + _BaseChatServiceRestTransport._BaseMarkAsActive._get_request_body_json( + transcoded_request + ) ) # Jsonify the query params - query_params = _BaseChatServiceRestTransport._BaseMoveSectionItem._get_query_params_json( - transcoded_request + query_params = ( + _BaseChatServiceRestTransport._BaseMarkAsActive._get_query_params_json( + transcoded_request + ) ) if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( @@ -7131,17 +7569,17 @@ def __call__( "headers": dict(metadata), } _LOGGER.debug( - f"Sending request for google.chat_v1.ChatServiceClient.MoveSectionItem", + f"Sending request for google.chat_v1.ChatServiceClient.MarkAsActive", extra={ "serviceName": "google.chat.v1.ChatService", - "rpcName": "MoveSectionItem", + "rpcName": "MarkAsActive", "httpRequest": http_request, "metadata": http_request["headers"], }, ) # Send the request - response = ChatServiceRestTransport._MoveSectionItem._get_response( + response = ChatServiceRestTransport._MarkAsActive._get_response( self._host, metadata, query_params, @@ -7157,21 +7595,21 @@ def __call__( raise core_exceptions.from_http_response(response) # Return the response - resp = section.MoveSectionItemResponse() - pb_resp = section.MoveSectionItemResponse.pb(resp) + resp = availability.Availability() + pb_resp = availability.Availability.pb(resp) json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_move_section_item(resp) + resp = self._interceptor.post_mark_as_active(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_move_section_item_with_metadata( + resp, _ = self._interceptor.post_mark_as_active_with_metadata( resp, response_metadata ) if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( logging.DEBUG ): # pragma: NO COVER try: - response_payload = section.MoveSectionItemResponse.to_json(response) + response_payload = availability.Availability.to_json(response) except: response_payload = None http_response = { @@ -7180,21 +7618,21 @@ def __call__( "status": response.status_code, } _LOGGER.debug( - "Received response for google.chat_v1.ChatServiceClient.move_section_item", + "Received response for google.chat_v1.ChatServiceClient.mark_as_active", extra={ "serviceName": "google.chat.v1.ChatService", - "rpcName": "MoveSectionItem", + "rpcName": "MarkAsActive", "metadata": http_response["headers"], "httpResponse": http_response, }, ) return resp - class _PositionSection( - _BaseChatServiceRestTransport._BasePositionSection, ChatServiceRestStub + class _MarkAsAway( + _BaseChatServiceRestTransport._BaseMarkAsAway, ChatServiceRestStub ): def __hash__(self): - return hash("ChatServiceRestTransport.PositionSection") + return hash("ChatServiceRestTransport.MarkAsAway") @staticmethod def _get_response( @@ -7221,18 +7659,17 @@ def _get_response( def __call__( self, - request: section.PositionSectionRequest, + request: availability.MarkAsAwayRequest, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> section.PositionSectionResponse: - r"""Call the position section method over HTTP. + ) -> availability.Availability: + r"""Call the mark as away method over HTTP. Args: - request (~.section.PositionSectionRequest): - The request object. Request message for positioning a - section. + request (~.availability.MarkAsAwayRequest): + The request object. Request message for the ``MarkAsAway`` method. retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -7242,30 +7679,35 @@ def __call__( be of type `bytes`. Returns: - ~.section.PositionSectionResponse: - Response message for positioning a - section. + ~.availability.Availability: + Represents a user's current + availability information in Google Chat, + including their state (for example, + Active, Away, Do Not Disturb) and any + custom status. """ http_options = ( - _BaseChatServiceRestTransport._BasePositionSection._get_http_options() + _BaseChatServiceRestTransport._BaseMarkAsAway._get_http_options() ) - request, metadata = self._interceptor.pre_position_section( - request, metadata - ) - transcoded_request = _BaseChatServiceRestTransport._BasePositionSection._get_transcoded_request( - http_options, request + request, metadata = self._interceptor.pre_mark_as_away(request, metadata) + transcoded_request = ( + _BaseChatServiceRestTransport._BaseMarkAsAway._get_transcoded_request( + http_options, request + ) ) - body = _BaseChatServiceRestTransport._BasePositionSection._get_request_body_json( + body = _BaseChatServiceRestTransport._BaseMarkAsAway._get_request_body_json( transcoded_request ) # Jsonify the query params - query_params = _BaseChatServiceRestTransport._BasePositionSection._get_query_params_json( - transcoded_request + query_params = ( + _BaseChatServiceRestTransport._BaseMarkAsAway._get_query_params_json( + transcoded_request + ) ) if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( @@ -7286,17 +7728,17 @@ def __call__( "headers": dict(metadata), } _LOGGER.debug( - f"Sending request for google.chat_v1.ChatServiceClient.PositionSection", + f"Sending request for google.chat_v1.ChatServiceClient.MarkAsAway", extra={ "serviceName": "google.chat.v1.ChatService", - "rpcName": "PositionSection", + "rpcName": "MarkAsAway", "httpRequest": http_request, "metadata": http_request["headers"], }, ) # Send the request - response = ChatServiceRestTransport._PositionSection._get_response( + response = ChatServiceRestTransport._MarkAsAway._get_response( self._host, metadata, query_params, @@ -7312,21 +7754,21 @@ def __call__( raise core_exceptions.from_http_response(response) # Return the response - resp = section.PositionSectionResponse() - pb_resp = section.PositionSectionResponse.pb(resp) + resp = availability.Availability() + pb_resp = availability.Availability.pb(resp) json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_position_section(resp) + resp = self._interceptor.post_mark_as_away(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_position_section_with_metadata( + resp, _ = self._interceptor.post_mark_as_away_with_metadata( resp, response_metadata ) if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( logging.DEBUG ): # pragma: NO COVER try: - response_payload = section.PositionSectionResponse.to_json(response) + response_payload = availability.Availability.to_json(response) except: response_payload = None http_response = { @@ -7335,21 +7777,21 @@ def __call__( "status": response.status_code, } _LOGGER.debug( - "Received response for google.chat_v1.ChatServiceClient.position_section", + "Received response for google.chat_v1.ChatServiceClient.mark_as_away", extra={ "serviceName": "google.chat.v1.ChatService", - "rpcName": "PositionSection", + "rpcName": "MarkAsAway", "metadata": http_response["headers"], "httpResponse": http_response, }, ) return resp - class _SearchSpaces( - _BaseChatServiceRestTransport._BaseSearchSpaces, ChatServiceRestStub + class _MarkAsDoNotDisturb( + _BaseChatServiceRestTransport._BaseMarkAsDoNotDisturb, ChatServiceRestStub ): def __hash__(self): - return hash("ChatServiceRestTransport.SearchSpaces") + return hash("ChatServiceRestTransport.MarkAsDoNotDisturb") @staticmethod def _get_response( @@ -7370,23 +7812,23 @@ def _get_response( timeout=timeout, headers=headers, params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, ) return response def __call__( self, - request: space.SearchSpacesRequest, + request: availability.MarkAsDoNotDisturbRequest, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> space.SearchSpacesResponse: - r"""Call the search spaces method over HTTP. + ) -> availability.Availability: + r"""Call the mark as do not disturb method over HTTP. Args: - request (~.space.SearchSpacesRequest): - The request object. Request to search for a list of - spaces based on a query. + request (~.availability.MarkAsDoNotDisturbRequest): + The request object. Request message for the ``MarkAsDoNotDisturb`` method. retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -7396,26 +7838,491 @@ def __call__( be of type `bytes`. Returns: - ~.space.SearchSpacesResponse: - Response with a list of spaces - corresponding to the search spaces - request. + ~.availability.Availability: + Represents a user's current + availability information in Google Chat, + including their state (for example, + Active, Away, Do Not Disturb) and any + custom status. """ - http_options = ( - _BaseChatServiceRestTransport._BaseSearchSpaces._get_http_options() + http_options = _BaseChatServiceRestTransport._BaseMarkAsDoNotDisturb._get_http_options() + + request, metadata = self._interceptor.pre_mark_as_do_not_disturb( + request, metadata + ) + transcoded_request = _BaseChatServiceRestTransport._BaseMarkAsDoNotDisturb._get_transcoded_request( + http_options, request ) - request, metadata = self._interceptor.pre_search_spaces(request, metadata) - transcoded_request = ( - _BaseChatServiceRestTransport._BaseSearchSpaces._get_transcoded_request( - http_options, request - ) + body = _BaseChatServiceRestTransport._BaseMarkAsDoNotDisturb._get_request_body_json( + transcoded_request ) # Jsonify the query params - query_params = ( + query_params = _BaseChatServiceRestTransport._BaseMarkAsDoNotDisturb._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.MarkAsDoNotDisturb", + extra={ + "serviceName": "google.chat.v1.ChatService", + "rpcName": "MarkAsDoNotDisturb", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = ChatServiceRestTransport._MarkAsDoNotDisturb._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 = availability.Availability() + pb_resp = availability.Availability.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_mark_as_do_not_disturb(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_mark_as_do_not_disturb_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = availability.Availability.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.mark_as_do_not_disturb", + extra={ + "serviceName": "google.chat.v1.ChatService", + "rpcName": "MarkAsDoNotDisturb", + "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]]] = (), + ) -> section.MoveSectionItemResponse: + r"""Call the move section item method over HTTP. + + Args: + 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. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each 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.MoveSectionItemResponse: + Response message for moving a section + item. + + """ + + http_options = ( + _BaseChatServiceRestTransport._BaseMoveSectionItem._get_http_options() + ) + + request, metadata = self._interceptor.pre_move_section_item( + request, metadata + ) + 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._BaseMoveSectionItem._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.MoveSectionItem", + extra={ + "serviceName": "google.chat.v1.ChatService", + "rpcName": "MoveSectionItem", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + 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 + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = section.MoveSectionItemResponse() + pb_resp = section.MoveSectionItemResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_move_section_item(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + 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 = section.MoveSectionItemResponse.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.move_section_item", + extra={ + "serviceName": "google.chat.v1.ChatService", + "rpcName": "MoveSectionItem", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _PositionSection( + _BaseChatServiceRestTransport._BasePositionSection, ChatServiceRestStub + ): + def __hash__(self): + return hash("ChatServiceRestTransport.PositionSection") + + @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.PositionSectionRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> section.PositionSectionResponse: + r"""Call the position section method over HTTP. + + Args: + 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. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each 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.PositionSectionResponse: + Response message for positioning a + section. + + """ + + http_options = ( + _BaseChatServiceRestTransport._BasePositionSection._get_http_options() + ) + + 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._BasePositionSection._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.PositionSection", + extra={ + "serviceName": "google.chat.v1.ChatService", + "rpcName": "PositionSection", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + 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 + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = section.PositionSectionResponse() + pb_resp = section.PositionSectionResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_position_section(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + 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 = section.PositionSectionResponse.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.position_section", + extra={ + "serviceName": "google.chat.v1.ChatService", + "rpcName": "PositionSection", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _SearchSpaces( + _BaseChatServiceRestTransport._BaseSearchSpaces, ChatServiceRestStub + ): + def __hash__(self): + return hash("ChatServiceRestTransport.SearchSpaces") + + @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.SearchSpacesRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> space.SearchSpacesResponse: + r"""Call the search spaces method over HTTP. + + Args: + request (~.space.SearchSpacesRequest): + The request object. Request to search for a list of + spaces based on a query. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each 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.SearchSpacesResponse: + Response with a list of spaces + corresponding to the search spaces + request. + + """ + + http_options = ( + _BaseChatServiceRestTransport._BaseSearchSpaces._get_http_options() + ) + + request, metadata = self._interceptor.pre_search_spaces(request, metadata) + transcoded_request = ( + _BaseChatServiceRestTransport._BaseSearchSpaces._get_transcoded_request( + http_options, request + ) + ) + + # Jsonify the query params + query_params = ( _BaseChatServiceRestTransport._BaseSearchSpaces._get_query_params_json( transcoded_request ) @@ -7656,6 +8563,161 @@ def __call__( ) return resp + class _UpdateAvailability( + _BaseChatServiceRestTransport._BaseUpdateAvailability, ChatServiceRestStub + ): + def __hash__(self): + return hash("ChatServiceRestTransport.UpdateAvailability") + + @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_availability.UpdateAvailabilityRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> gc_availability.Availability: + r"""Call the update availability method over HTTP. + + Args: + request (~.gc_availability.UpdateAvailabilityRequest): + The request object. Request message for the ``UpdateAvailability`` method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.gc_availability.Availability: + Represents a user's current + availability information in Google Chat, + including their state (for example, + Active, Away, Do Not Disturb) and any + custom status. + + """ + + http_options = _BaseChatServiceRestTransport._BaseUpdateAvailability._get_http_options() + + request, metadata = self._interceptor.pre_update_availability( + request, metadata + ) + transcoded_request = _BaseChatServiceRestTransport._BaseUpdateAvailability._get_transcoded_request( + http_options, request + ) + + body = _BaseChatServiceRestTransport._BaseUpdateAvailability._get_request_body_json( + transcoded_request + ) + + # Jsonify the query params + query_params = _BaseChatServiceRestTransport._BaseUpdateAvailability._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.UpdateAvailability", + extra={ + "serviceName": "google.chat.v1.ChatService", + "rpcName": "UpdateAvailability", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = ChatServiceRestTransport._UpdateAvailability._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_availability.Availability() + pb_resp = gc_availability.Availability.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_update_availability(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_update_availability_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = gc_availability.Availability.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_availability", + extra={ + "serviceName": "google.chat.v1.ChatService", + "rpcName": "UpdateAvailability", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + class _UpdateMembership( _BaseChatServiceRestTransport._BaseUpdateMembership, ChatServiceRestStub ): @@ -8903,6 +9965,14 @@ def get_attachment( # In C++ this would require a dynamic_cast return self._GetAttachment(self._session, self._host, self._interceptor) # type: ignore + @property + def get_availability( + self, + ) -> Callable[[availability.GetAvailabilityRequest], availability.Availability]: + # 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._GetAvailability(self._session, self._host, self._interceptor) # type: ignore + @property def get_custom_emoji( self, @@ -9042,6 +10112,30 @@ def list_spaces( # In C++ this would require a dynamic_cast return self._ListSpaces(self._session, self._host, self._interceptor) # type: ignore + @property + def mark_as_active( + self, + ) -> Callable[[availability.MarkAsActiveRequest], availability.Availability]: + # 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._MarkAsActive(self._session, self._host, self._interceptor) # type: ignore + + @property + def mark_as_away( + self, + ) -> Callable[[availability.MarkAsAwayRequest], availability.Availability]: + # 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._MarkAsAway(self._session, self._host, self._interceptor) # type: ignore + + @property + def mark_as_do_not_disturb( + self, + ) -> Callable[[availability.MarkAsDoNotDisturbRequest], availability.Availability]: + # 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._MarkAsDoNotDisturb(self._session, self._host, self._interceptor) # type: ignore + @property def move_section_item( self, @@ -9072,6 +10166,16 @@ def set_up_space(self) -> Callable[[space_setup.SetUpSpaceRequest], space.Space] # In C++ this would require a dynamic_cast return self._SetUpSpace(self._session, self._host, self._interceptor) # type: ignore + @property + def update_availability( + self, + ) -> Callable[ + [gc_availability.UpdateAvailabilityRequest], gc_availability.Availability + ]: + # 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._UpdateAvailability(self._session, self._host, self._interceptor) # type: ignore + @property def update_membership( self, 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 ab5a278baa25..87e8eabafc2f 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 @@ -23,6 +23,7 @@ from google.apps.chat_v1.types import ( attachment, + availability, membership, message, reaction, @@ -34,6 +35,7 @@ space_setup, thread_read_state, ) +from google.apps.chat_v1.types import availability as gc_availability 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 @@ -918,6 +920,53 @@ def _get_query_params_json(transcoded_request): query_params["$alt"] = "json;enum-encoding=int" return query_params + class _BaseGetAvailability: + 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/{name=users/*/availability}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = availability.GetAvailabilityRequest.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._BaseGetAvailability._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + class _BaseGetCustomEmoji: def __hash__(self): # pragma: NO COVER return NotImplementedError("__hash__ must be implemented.") @@ -1646,6 +1695,177 @@ def _get_query_params_json(transcoded_request): query_params["$alt"] = "json;enum-encoding=int" return query_params + class _BaseMarkAsActive: + 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/*/availability}:markAsActive", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = availability.MarkAsActiveRequest.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._BaseMarkAsActive._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseMarkAsAway: + 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/*/availability}:markAsAway", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = availability.MarkAsAwayRequest.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._BaseMarkAsAway._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseMarkAsDoNotDisturb: + 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/*/availability}:markAsDoNotDisturb", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = availability.MarkAsDoNotDisturbRequest.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._BaseMarkAsDoNotDisturb._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + class _BaseMoveSectionItem: def __hash__(self): # pragma: NO COVER return NotImplementedError("__hash__ must be implemented.") @@ -1866,6 +2086,65 @@ def _get_query_params_json(transcoded_request): query_params["$alt"] = "json;enum-encoding=int" return query_params + class _BaseUpdateAvailability: + 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/{availability.name=users/*/availability}", + "body": "availability", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = gc_availability.UpdateAvailabilityRequest.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._BaseUpdateAvailability._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + class _BaseUpdateMembership: 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 9a1f3c484828..7789b20893be 100644 --- a/packages/google-apps-chat/google/apps/chat_v1/types/__init__.py +++ b/packages/google-apps-chat/google/apps/chat_v1/types/__init__.py @@ -36,6 +36,16 @@ UploadAttachmentRequest, UploadAttachmentResponse, ) +from .availability import ( + Availability, + CustomStatus, + DoNotDisturbMetadata, + GetAvailabilityRequest, + MarkAsActiveRequest, + MarkAsAwayRequest, + MarkAsDoNotDisturbRequest, + UpdateAvailabilityRequest, +) from .contextual_addon import ( ContextualAddOnMarkup, ) @@ -198,6 +208,14 @@ "GetAttachmentRequest", "UploadAttachmentRequest", "UploadAttachmentResponse", + "Availability", + "CustomStatus", + "DoNotDisturbMetadata", + "GetAvailabilityRequest", + "MarkAsActiveRequest", + "MarkAsAwayRequest", + "MarkAsDoNotDisturbRequest", + "UpdateAvailabilityRequest", "ContextualAddOnMarkup", "DeletionMetadata", "MembershipBatchCreatedEventData", diff --git a/packages/google-apps-chat/google/apps/chat_v1/types/availability.py b/packages/google-apps-chat/google/apps/chat_v1/types/availability.py new file mode 100644 index 000000000000..76ea0d3174d9 --- /dev/null +++ b/packages/google-apps-chat/google/apps/chat_v1/types/availability.py @@ -0,0 +1,371 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import google.protobuf.duration_pb2 as duration_pb2 # type: ignore +import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore +import google.protobuf.timestamp_pb2 as timestamp_pb2 # type: ignore +import proto # type: ignore + +from google.apps.chat_v1.types import reaction + +__protobuf__ = proto.module( + package="google.chat.v1", + manifest={ + "Availability", + "CustomStatus", + "DoNotDisturbMetadata", + "GetAvailabilityRequest", + "UpdateAvailabilityRequest", + "MarkAsActiveRequest", + "MarkAsAwayRequest", + "MarkAsDoNotDisturbRequest", + }, +) + + +class Availability(proto.Message): + r"""Represents a user's current availability information in + Google Chat, including their state (for example, Active, Away, + Do Not Disturb) and any custom status. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + name (str): + Identifier. Resource name of the user's availability. + + Format: ``users/{user}/availability`` + + ``{user}`` is the id for the Person in the People API or + Admin SDK directory API. For example, ``users/123456789``. + + The user's email address or ``me`` can also be used as an + alias to refer to the caller. For example, + ``users/user@example.com`` or ``users/me``. + state (google.apps.chat_v1.types.Availability.State): + Output only. The user's current availability + state. + do_not_disturb_metadata (google.apps.chat_v1.types.DoNotDisturbMetadata): + Output only. Metadata if the user state is set to + DO_NOT_DISTURB. + + This field is a member of `oneof`_ ``state_metadata``. + custom_status (google.apps.chat_v1.types.CustomStatus): + Optional. The user's custom status. + """ + + class State(proto.Enum): + r"""Represents the current availability state of the user. + + Values: + STATE_UNSPECIFIED (0): + Default value. The state is unspecified. + ACTIVE (1): + The user is currently active, based on recent + activity. + IDLE (2): + The user is currently idle. This state + indicates a period of inactivity after being + ACTIVE, before potentially transitioning to + AWAY. + AWAY (3): + The user is currently away. This can be either automatically + set after a period of inactivity in ACTIVE or IDLE state, or + it can be manually set by the user. When manually set via + ``MarkAsAway``, this state persists regardless of user + activity. + DO_NOT_DISTURB (4): + The user is in Do Not Disturb state, which is + manually set. + """ + + STATE_UNSPECIFIED = 0 + ACTIVE = 1 + IDLE = 2 + AWAY = 3 + DO_NOT_DISTURB = 4 + + name: str = proto.Field( + proto.STRING, + number=1, + ) + state: State = proto.Field( + proto.ENUM, + number=2, + enum=State, + ) + do_not_disturb_metadata: "DoNotDisturbMetadata" = proto.Field( + proto.MESSAGE, + number=3, + oneof="state_metadata", + message="DoNotDisturbMetadata", + ) + custom_status: "CustomStatus" = proto.Field( + proto.MESSAGE, + number=4, + message="CustomStatus", + ) + + +class CustomStatus(proto.Message): + r"""Represents a user's custom status in Google Chat. + This includes a short text message with an optional emoji that a + user sets to give more context about their availability. + + 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: + text (str): + Required. The text of the custom status. This + will be a string with maximum length of 64. + emoji (google.apps.chat_v1.types.Emoji): + Required. The emoji of the custom status. + Only Unicode emojis are supported; custom emojis + are not supported. + expire_time (google.protobuf.timestamp_pb2.Timestamp): + The timestamp when the custom status expires. + + This field is a member of `oneof`_ ``expiration``. + ttl (google.protobuf.duration_pb2.Duration): + Input only. The time-to-live duration after + which the custom status expires. + + This field is a member of `oneof`_ ``expiration``. + """ + + text: str = proto.Field( + proto.STRING, + number=1, + ) + emoji: reaction.Emoji = proto.Field( + proto.MESSAGE, + number=2, + message=reaction.Emoji, + ) + expire_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=3, + oneof="expiration", + message=timestamp_pb2.Timestamp, + ) + ttl: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=4, + oneof="expiration", + message=duration_pb2.Duration, + ) + + +class DoNotDisturbMetadata(proto.Message): + r"""Metadata associated with the ``DO_NOT_DISTURB`` availability state, + specifying when the state is set to expire. + + Attributes: + expiration_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Timestamp until which the user should be marked + as DO_NOT_DISTURB. This can be maximum of 1 year in the + future. + """ + + expiration_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=1, + message=timestamp_pb2.Timestamp, + ) + + +class GetAvailabilityRequest(proto.Message): + r"""Request message for the ``GetAvailability`` method. + + Attributes: + name (str): + Required. The resource name of the availability to retrieve. + + Format: users/{user}/availability + + ``{user}`` is the id for the Person in the People API or + Admin SDK directory API. For example, ``users/123456789``. + + The user's email address or ``me`` can also be used as an + alias to refer to the caller. For example, + ``users/user@example.com`` or ``users/me``. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class UpdateAvailabilityRequest(proto.Message): + r"""Request message for the ``UpdateAvailability`` method. + + Attributes: + availability (google.apps.chat_v1.types.Availability): + Required. The availability to update. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. The list of fields to update. The only field that + can be updated is ``custom_status``. + """ + + availability: "Availability" = proto.Field( + proto.MESSAGE, + number=1, + message="Availability", + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class MarkAsActiveRequest(proto.Message): + r"""Request message for the ``MarkAsActive`` method. + + 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 availability to mark as + active. Format: users/{user}/availability + + ``{user}`` is the id for the Person in the People API or + Admin SDK directory API. For example, ``users/123456789``. + + The user's email address or ``me`` can also be used as an + alias to refer to the caller. For example, + ``users/user@example.com`` or ``users/me``. + expire_time (google.protobuf.timestamp_pb2.Timestamp): + The absolute timestamp when the ACTIVE state + expires. + + This field is a member of `oneof`_ ``expiration``. + ttl (google.protobuf.duration_pb2.Duration): + The duration from the current time until the + ACTIVE state expires. Using a short TTL can + effectively reset the user's state to be based + on activity after this brief duration. + + This field is a member of `oneof`_ ``expiration``. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + expire_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + oneof="expiration", + message=timestamp_pb2.Timestamp, + ) + ttl: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=3, + oneof="expiration", + message=duration_pb2.Duration, + ) + + +class MarkAsAwayRequest(proto.Message): + r"""Request message for the ``MarkAsAway`` method. + + Attributes: + name (str): + Required. The resource name of the availability to mark as + away. Format: users/{user}/availability + + ``{user}`` is the id for the Person in the People API or + Admin SDK directory API. For example, ``users/123456789``. + + The user's email address or ``me`` can also be used as an + alias to refer to the caller. For example, + ``users/user@example.com`` or ``users/me``. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class MarkAsDoNotDisturbRequest(proto.Message): + r"""Request message for the ``MarkAsDoNotDisturb`` method. + + 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 availability to mark as + Do Not Disturb. Format: users/{user}/availability + + ``{user}`` is the id for the Person in the People API or + Admin SDK directory API. For example, ``users/123456789``. + + The user's email address or ``me`` can also be used as an + alias to refer to the caller. For example, + ``users/user@example.com`` or ``users/me``. + expire_time (google.protobuf.timestamp_pb2.Timestamp): + The absolute timestamp when the DND state + expires. + + This field is a member of `oneof`_ ``expiration``. + ttl (google.protobuf.duration_pb2.Duration): + The duration from the current time until the + DND state expires. + + This field is a member of `oneof`_ ``expiration``. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + expire_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + oneof="expiration", + message=timestamp_pb2.Timestamp, + ) + ttl: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=3, + oneof="expiration", + message=duration_pb2.Duration, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-apps-chat/samples/generated_samples/chat_v1_generated_chat_service_get_availability_async.py b/packages/google-apps-chat/samples/generated_samples/chat_v1_generated_chat_service_get_availability_async.py new file mode 100644 index 000000000000..7735a87c3e9e --- /dev/null +++ b/packages/google-apps-chat/samples/generated_samples/chat_v1_generated_chat_service_get_availability_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetAvailability +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# 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_GetAvailability_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_get_availability(): + # Create a client + client = chat_v1.ChatServiceAsyncClient() + + # Initialize request argument(s) + request = chat_v1.GetAvailabilityRequest( + name="name_value", + ) + + # Make the request + response = await client.get_availability(request=request) + + # Handle the response + print(response) + + +# [END chat_v1_generated_ChatService_GetAvailability_async] diff --git a/packages/google-apps-chat/samples/generated_samples/chat_v1_generated_chat_service_get_availability_sync.py b/packages/google-apps-chat/samples/generated_samples/chat_v1_generated_chat_service_get_availability_sync.py new file mode 100644 index 000000000000..fcb4f9fcd048 --- /dev/null +++ b/packages/google-apps-chat/samples/generated_samples/chat_v1_generated_chat_service_get_availability_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetAvailability +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# 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_GetAvailability_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_get_availability(): + # Create a client + client = chat_v1.ChatServiceClient() + + # Initialize request argument(s) + request = chat_v1.GetAvailabilityRequest( + name="name_value", + ) + + # Make the request + response = client.get_availability(request=request) + + # Handle the response + print(response) + + +# [END chat_v1_generated_ChatService_GetAvailability_sync] diff --git a/packages/google-apps-chat/samples/generated_samples/chat_v1_generated_chat_service_mark_as_active_async.py b/packages/google-apps-chat/samples/generated_samples/chat_v1_generated_chat_service_mark_as_active_async.py new file mode 100644 index 000000000000..e1182f5d645d --- /dev/null +++ b/packages/google-apps-chat/samples/generated_samples/chat_v1_generated_chat_service_mark_as_active_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for MarkAsActive +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# 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_MarkAsActive_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_mark_as_active(): + # Create a client + client = chat_v1.ChatServiceAsyncClient() + + # Initialize request argument(s) + request = chat_v1.MarkAsActiveRequest( + name="name_value", + ) + + # Make the request + response = await client.mark_as_active(request=request) + + # Handle the response + print(response) + + +# [END chat_v1_generated_ChatService_MarkAsActive_async] diff --git a/packages/google-apps-chat/samples/generated_samples/chat_v1_generated_chat_service_mark_as_active_sync.py b/packages/google-apps-chat/samples/generated_samples/chat_v1_generated_chat_service_mark_as_active_sync.py new file mode 100644 index 000000000000..9b75c193bff4 --- /dev/null +++ b/packages/google-apps-chat/samples/generated_samples/chat_v1_generated_chat_service_mark_as_active_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for MarkAsActive +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# 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_MarkAsActive_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_mark_as_active(): + # Create a client + client = chat_v1.ChatServiceClient() + + # Initialize request argument(s) + request = chat_v1.MarkAsActiveRequest( + name="name_value", + ) + + # Make the request + response = client.mark_as_active(request=request) + + # Handle the response + print(response) + + +# [END chat_v1_generated_ChatService_MarkAsActive_sync] diff --git a/packages/google-apps-chat/samples/generated_samples/chat_v1_generated_chat_service_mark_as_away_async.py b/packages/google-apps-chat/samples/generated_samples/chat_v1_generated_chat_service_mark_as_away_async.py new file mode 100644 index 000000000000..be51cb23938d --- /dev/null +++ b/packages/google-apps-chat/samples/generated_samples/chat_v1_generated_chat_service_mark_as_away_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for MarkAsAway +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# 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_MarkAsAway_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_mark_as_away(): + # Create a client + client = chat_v1.ChatServiceAsyncClient() + + # Initialize request argument(s) + request = chat_v1.MarkAsAwayRequest( + name="name_value", + ) + + # Make the request + response = await client.mark_as_away(request=request) + + # Handle the response + print(response) + + +# [END chat_v1_generated_ChatService_MarkAsAway_async] diff --git a/packages/google-apps-chat/samples/generated_samples/chat_v1_generated_chat_service_mark_as_away_sync.py b/packages/google-apps-chat/samples/generated_samples/chat_v1_generated_chat_service_mark_as_away_sync.py new file mode 100644 index 000000000000..5b6ab2c0d843 --- /dev/null +++ b/packages/google-apps-chat/samples/generated_samples/chat_v1_generated_chat_service_mark_as_away_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for MarkAsAway +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# 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_MarkAsAway_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_mark_as_away(): + # Create a client + client = chat_v1.ChatServiceClient() + + # Initialize request argument(s) + request = chat_v1.MarkAsAwayRequest( + name="name_value", + ) + + # Make the request + response = client.mark_as_away(request=request) + + # Handle the response + print(response) + + +# [END chat_v1_generated_ChatService_MarkAsAway_sync] diff --git a/packages/google-apps-chat/samples/generated_samples/chat_v1_generated_chat_service_mark_as_do_not_disturb_async.py b/packages/google-apps-chat/samples/generated_samples/chat_v1_generated_chat_service_mark_as_do_not_disturb_async.py new file mode 100644 index 000000000000..29bd7c14e69b --- /dev/null +++ b/packages/google-apps-chat/samples/generated_samples/chat_v1_generated_chat_service_mark_as_do_not_disturb_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for MarkAsDoNotDisturb +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# 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_MarkAsDoNotDisturb_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_mark_as_do_not_disturb(): + # Create a client + client = chat_v1.ChatServiceAsyncClient() + + # Initialize request argument(s) + request = chat_v1.MarkAsDoNotDisturbRequest( + name="name_value", + ) + + # Make the request + response = await client.mark_as_do_not_disturb(request=request) + + # Handle the response + print(response) + + +# [END chat_v1_generated_ChatService_MarkAsDoNotDisturb_async] diff --git a/packages/google-apps-chat/samples/generated_samples/chat_v1_generated_chat_service_mark_as_do_not_disturb_sync.py b/packages/google-apps-chat/samples/generated_samples/chat_v1_generated_chat_service_mark_as_do_not_disturb_sync.py new file mode 100644 index 000000000000..33468c0e9a8a --- /dev/null +++ b/packages/google-apps-chat/samples/generated_samples/chat_v1_generated_chat_service_mark_as_do_not_disturb_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for MarkAsDoNotDisturb +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# 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_MarkAsDoNotDisturb_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_mark_as_do_not_disturb(): + # Create a client + client = chat_v1.ChatServiceClient() + + # Initialize request argument(s) + request = chat_v1.MarkAsDoNotDisturbRequest( + name="name_value", + ) + + # Make the request + response = client.mark_as_do_not_disturb(request=request) + + # Handle the response + print(response) + + +# [END chat_v1_generated_ChatService_MarkAsDoNotDisturb_sync] diff --git a/packages/google-apps-chat/samples/generated_samples/chat_v1_generated_chat_service_update_availability_async.py b/packages/google-apps-chat/samples/generated_samples/chat_v1_generated_chat_service_update_availability_async.py new file mode 100644 index 000000000000..d078c287ec23 --- /dev/null +++ b/packages/google-apps-chat/samples/generated_samples/chat_v1_generated_chat_service_update_availability_async.py @@ -0,0 +1,51 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateAvailability +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# 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_UpdateAvailability_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_availability(): + # Create a client + client = chat_v1.ChatServiceAsyncClient() + + # Initialize request argument(s) + request = chat_v1.UpdateAvailabilityRequest() + + # Make the request + response = await client.update_availability(request=request) + + # Handle the response + print(response) + + +# [END chat_v1_generated_ChatService_UpdateAvailability_async] diff --git a/packages/google-apps-chat/samples/generated_samples/chat_v1_generated_chat_service_update_availability_sync.py b/packages/google-apps-chat/samples/generated_samples/chat_v1_generated_chat_service_update_availability_sync.py new file mode 100644 index 000000000000..872a264a0fb3 --- /dev/null +++ b/packages/google-apps-chat/samples/generated_samples/chat_v1_generated_chat_service_update_availability_sync.py @@ -0,0 +1,51 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateAvailability +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# 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_UpdateAvailability_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_availability(): + # Create a client + client = chat_v1.ChatServiceClient() + + # Initialize request argument(s) + request = chat_v1.UpdateAvailabilityRequest() + + # Make the request + response = client.update_availability(request=request) + + # Handle the response + print(response) + + +# [END chat_v1_generated_ChatService_UpdateAvailability_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 ee167e678f8d..2dbacac7507b 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 @@ -2573,6 +2573,167 @@ ], "title": "chat_v1_generated_chat_service_get_attachment_sync.py" }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.apps.chat_v1.ChatServiceAsyncClient", + "shortName": "ChatServiceAsyncClient" + }, + "fullName": "google.apps.chat_v1.ChatServiceAsyncClient.get_availability", + "method": { + "fullName": "google.chat.v1.ChatService.GetAvailability", + "service": { + "fullName": "google.chat.v1.ChatService", + "shortName": "ChatService" + }, + "shortName": "GetAvailability" + }, + "parameters": [ + { + "name": "request", + "type": "google.apps.chat_v1.types.GetAvailabilityRequest" + }, + { + "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.Availability", + "shortName": "get_availability" + }, + "description": "Sample for GetAvailability", + "file": "chat_v1_generated_chat_service_get_availability_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "chat_v1_generated_ChatService_GetAvailability_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_availability_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.apps.chat_v1.ChatServiceClient", + "shortName": "ChatServiceClient" + }, + "fullName": "google.apps.chat_v1.ChatServiceClient.get_availability", + "method": { + "fullName": "google.chat.v1.ChatService.GetAvailability", + "service": { + "fullName": "google.chat.v1.ChatService", + "shortName": "ChatService" + }, + "shortName": "GetAvailability" + }, + "parameters": [ + { + "name": "request", + "type": "google.apps.chat_v1.types.GetAvailabilityRequest" + }, + { + "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.Availability", + "shortName": "get_availability" + }, + "description": "Sample for GetAvailability", + "file": "chat_v1_generated_chat_service_get_availability_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "chat_v1_generated_ChatService_GetAvailability_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_get_availability_sync.py" + }, { "canonical": true, "clientMethod": { @@ -5149,27 +5310,19 @@ "fullName": "google.apps.chat_v1.ChatServiceAsyncClient", "shortName": "ChatServiceAsyncClient" }, - "fullName": "google.apps.chat_v1.ChatServiceAsyncClient.move_section_item", + "fullName": "google.apps.chat_v1.ChatServiceAsyncClient.mark_as_active", "method": { - "fullName": "google.chat.v1.ChatService.MoveSectionItem", + "fullName": "google.chat.v1.ChatService.MarkAsActive", "service": { "fullName": "google.chat.v1.ChatService", "shortName": "ChatService" }, - "shortName": "MoveSectionItem" + "shortName": "MarkAsActive" }, "parameters": [ { "name": "request", - "type": "google.apps.chat_v1.types.MoveSectionItemRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "target_section", - "type": "str" + "type": "google.apps.chat_v1.types.MarkAsActiveRequest" }, { "name": "retry", @@ -5184,22 +5337,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.apps.chat_v1.types.MoveSectionItemResponse", - "shortName": "move_section_item" + "resultType": "google.apps.chat_v1.types.Availability", + "shortName": "mark_as_active" }, - "description": "Sample for MoveSectionItem", - "file": "chat_v1_generated_chat_service_move_section_item_async.py", + "description": "Sample for MarkAsActive", + "file": "chat_v1_generated_chat_service_mark_as_active_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "chat_v1_generated_ChatService_MoveSectionItem_async", + "regionTag": "chat_v1_generated_ChatService_MarkAsActive_async", "segments": [ { - "end": 52, + "end": 51, "start": 27, "type": "FULL" }, { - "end": 52, + "end": 51, "start": 27, "type": "SHORT" }, @@ -5209,22 +5362,22 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 46, + "end": 45, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 49, - "start": 47, + "end": 48, + "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 53, - "start": 50, + "end": 52, + "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "chat_v1_generated_chat_service_move_section_item_async.py" + "title": "chat_v1_generated_chat_service_mark_as_active_async.py" }, { "canonical": true, @@ -5233,27 +5386,19 @@ "fullName": "google.apps.chat_v1.ChatServiceClient", "shortName": "ChatServiceClient" }, - "fullName": "google.apps.chat_v1.ChatServiceClient.move_section_item", + "fullName": "google.apps.chat_v1.ChatServiceClient.mark_as_active", "method": { - "fullName": "google.chat.v1.ChatService.MoveSectionItem", + "fullName": "google.chat.v1.ChatService.MarkAsActive", "service": { "fullName": "google.chat.v1.ChatService", "shortName": "ChatService" }, - "shortName": "MoveSectionItem" + "shortName": "MarkAsActive" }, "parameters": [ { "name": "request", - "type": "google.apps.chat_v1.types.MoveSectionItemRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "target_section", - "type": "str" + "type": "google.apps.chat_v1.types.MarkAsActiveRequest" }, { "name": "retry", @@ -5268,22 +5413,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.apps.chat_v1.types.MoveSectionItemResponse", - "shortName": "move_section_item" + "resultType": "google.apps.chat_v1.types.Availability", + "shortName": "mark_as_active" }, - "description": "Sample for MoveSectionItem", - "file": "chat_v1_generated_chat_service_move_section_item_sync.py", + "description": "Sample for MarkAsActive", + "file": "chat_v1_generated_chat_service_mark_as_active_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "chat_v1_generated_ChatService_MoveSectionItem_sync", + "regionTag": "chat_v1_generated_ChatService_MarkAsActive_sync", "segments": [ { - "end": 52, + "end": 51, "start": 27, "type": "FULL" }, { - "end": 52, + "end": 51, "start": 27, "type": "SHORT" }, @@ -5293,22 +5438,22 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 46, + "end": 45, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 49, - "start": 47, + "end": 48, + "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 53, - "start": 50, + "end": 52, + "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "chat_v1_generated_chat_service_move_section_item_sync.py" + "title": "chat_v1_generated_chat_service_mark_as_active_sync.py" }, { "canonical": true, @@ -5318,19 +5463,19 @@ "fullName": "google.apps.chat_v1.ChatServiceAsyncClient", "shortName": "ChatServiceAsyncClient" }, - "fullName": "google.apps.chat_v1.ChatServiceAsyncClient.position_section", + "fullName": "google.apps.chat_v1.ChatServiceAsyncClient.mark_as_away", "method": { - "fullName": "google.chat.v1.ChatService.PositionSection", + "fullName": "google.chat.v1.ChatService.MarkAsAway", "service": { "fullName": "google.chat.v1.ChatService", "shortName": "ChatService" }, - "shortName": "PositionSection" + "shortName": "MarkAsAway" }, "parameters": [ { "name": "request", - "type": "google.apps.chat_v1.types.PositionSectionRequest" + "type": "google.apps.chat_v1.types.MarkAsAwayRequest" }, { "name": "retry", @@ -5345,22 +5490,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.apps.chat_v1.types.PositionSectionResponse", - "shortName": "position_section" + "resultType": "google.apps.chat_v1.types.Availability", + "shortName": "mark_as_away" }, - "description": "Sample for PositionSection", - "file": "chat_v1_generated_chat_service_position_section_async.py", + "description": "Sample for MarkAsAway", + "file": "chat_v1_generated_chat_service_mark_as_away_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "chat_v1_generated_ChatService_PositionSection_async", + "regionTag": "chat_v1_generated_ChatService_MarkAsAway_async", "segments": [ { - "end": 52, + "end": 51, "start": 27, "type": "FULL" }, { - "end": 52, + "end": 51, "start": 27, "type": "SHORT" }, @@ -5370,22 +5515,22 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 46, + "end": 45, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 49, - "start": 47, + "end": 48, + "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 53, - "start": 50, + "end": 52, + "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "chat_v1_generated_chat_service_position_section_async.py" + "title": "chat_v1_generated_chat_service_mark_as_away_async.py" }, { "canonical": true, @@ -5394,19 +5539,19 @@ "fullName": "google.apps.chat_v1.ChatServiceClient", "shortName": "ChatServiceClient" }, - "fullName": "google.apps.chat_v1.ChatServiceClient.position_section", + "fullName": "google.apps.chat_v1.ChatServiceClient.mark_as_away", "method": { - "fullName": "google.chat.v1.ChatService.PositionSection", + "fullName": "google.chat.v1.ChatService.MarkAsAway", "service": { "fullName": "google.chat.v1.ChatService", "shortName": "ChatService" }, - "shortName": "PositionSection" + "shortName": "MarkAsAway" }, "parameters": [ { "name": "request", - "type": "google.apps.chat_v1.types.PositionSectionRequest" + "type": "google.apps.chat_v1.types.MarkAsAwayRequest" }, { "name": "retry", @@ -5421,22 +5566,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.apps.chat_v1.types.PositionSectionResponse", - "shortName": "position_section" + "resultType": "google.apps.chat_v1.types.Availability", + "shortName": "mark_as_away" }, - "description": "Sample for PositionSection", - "file": "chat_v1_generated_chat_service_position_section_sync.py", + "description": "Sample for MarkAsAway", + "file": "chat_v1_generated_chat_service_mark_as_away_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "chat_v1_generated_ChatService_PositionSection_sync", + "regionTag": "chat_v1_generated_ChatService_MarkAsAway_sync", "segments": [ { - "end": 52, + "end": 51, "start": 27, "type": "FULL" }, { - "end": 52, + "end": 51, "start": 27, "type": "SHORT" }, @@ -5446,22 +5591,22 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 46, + "end": 45, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 49, - "start": 47, + "end": 48, + "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 53, - "start": 50, + "end": 52, + "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "chat_v1_generated_chat_service_position_section_sync.py" + "title": "chat_v1_generated_chat_service_mark_as_away_sync.py" }, { "canonical": true, @@ -5471,14 +5616,489 @@ "fullName": "google.apps.chat_v1.ChatServiceAsyncClient", "shortName": "ChatServiceAsyncClient" }, - "fullName": "google.apps.chat_v1.ChatServiceAsyncClient.search_spaces", + "fullName": "google.apps.chat_v1.ChatServiceAsyncClient.mark_as_do_not_disturb", "method": { - "fullName": "google.chat.v1.ChatService.SearchSpaces", + "fullName": "google.chat.v1.ChatService.MarkAsDoNotDisturb", "service": { "fullName": "google.chat.v1.ChatService", "shortName": "ChatService" }, - "shortName": "SearchSpaces" + "shortName": "MarkAsDoNotDisturb" + }, + "parameters": [ + { + "name": "request", + "type": "google.apps.chat_v1.types.MarkAsDoNotDisturbRequest" + }, + { + "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.Availability", + "shortName": "mark_as_do_not_disturb" + }, + "description": "Sample for MarkAsDoNotDisturb", + "file": "chat_v1_generated_chat_service_mark_as_do_not_disturb_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "chat_v1_generated_ChatService_MarkAsDoNotDisturb_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_mark_as_do_not_disturb_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.apps.chat_v1.ChatServiceClient", + "shortName": "ChatServiceClient" + }, + "fullName": "google.apps.chat_v1.ChatServiceClient.mark_as_do_not_disturb", + "method": { + "fullName": "google.chat.v1.ChatService.MarkAsDoNotDisturb", + "service": { + "fullName": "google.chat.v1.ChatService", + "shortName": "ChatService" + }, + "shortName": "MarkAsDoNotDisturb" + }, + "parameters": [ + { + "name": "request", + "type": "google.apps.chat_v1.types.MarkAsDoNotDisturbRequest" + }, + { + "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.Availability", + "shortName": "mark_as_do_not_disturb" + }, + "description": "Sample for MarkAsDoNotDisturb", + "file": "chat_v1_generated_chat_service_mark_as_do_not_disturb_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "chat_v1_generated_ChatService_MarkAsDoNotDisturb_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_mark_as_do_not_disturb_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": 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_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": 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_position_section_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.apps.chat_v1.ChatServiceAsyncClient", + "shortName": "ChatServiceAsyncClient" + }, + "fullName": "google.apps.chat_v1.ChatServiceAsyncClient.search_spaces", + "method": { + "fullName": "google.chat.v1.ChatService.SearchSpaces", + "service": { + "fullName": "google.chat.v1.ChatService", + "shortName": "ChatService" + }, + "shortName": "SearchSpaces" }, "parameters": [ { @@ -5769,6 +6389,175 @@ ], "title": "chat_v1_generated_chat_service_set_up_space_sync.py" }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.apps.chat_v1.ChatServiceAsyncClient", + "shortName": "ChatServiceAsyncClient" + }, + "fullName": "google.apps.chat_v1.ChatServiceAsyncClient.update_availability", + "method": { + "fullName": "google.chat.v1.ChatService.UpdateAvailability", + "service": { + "fullName": "google.chat.v1.ChatService", + "shortName": "ChatService" + }, + "shortName": "UpdateAvailability" + }, + "parameters": [ + { + "name": "request", + "type": "google.apps.chat_v1.types.UpdateAvailabilityRequest" + }, + { + "name": "availability", + "type": "google.apps.chat_v1.types.Availability" + }, + { + "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.Availability", + "shortName": "update_availability" + }, + "description": "Sample for UpdateAvailability", + "file": "chat_v1_generated_chat_service_update_availability_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "chat_v1_generated_ChatService_UpdateAvailability_async", + "segments": [ + { + "end": 50, + "start": 27, + "type": "FULL" + }, + { + "end": 50, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 47, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 51, + "start": 48, + "type": "RESPONSE_HANDLING" + } + ], + "title": "chat_v1_generated_chat_service_update_availability_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.apps.chat_v1.ChatServiceClient", + "shortName": "ChatServiceClient" + }, + "fullName": "google.apps.chat_v1.ChatServiceClient.update_availability", + "method": { + "fullName": "google.chat.v1.ChatService.UpdateAvailability", + "service": { + "fullName": "google.chat.v1.ChatService", + "shortName": "ChatService" + }, + "shortName": "UpdateAvailability" + }, + "parameters": [ + { + "name": "request", + "type": "google.apps.chat_v1.types.UpdateAvailabilityRequest" + }, + { + "name": "availability", + "type": "google.apps.chat_v1.types.Availability" + }, + { + "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.Availability", + "shortName": "update_availability" + }, + "description": "Sample for UpdateAvailability", + "file": "chat_v1_generated_chat_service_update_availability_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "chat_v1_generated_ChatService_UpdateAvailability_sync", + "segments": [ + { + "end": 50, + "start": 27, + "type": "FULL" + }, + { + "end": 50, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 47, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 51, + "start": 48, + "type": "RESPONSE_HANDLING" + } + ], + "title": "chat_v1_generated_chat_service_update_availability_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 833b2f207c53..bc3edb2434ef 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 @@ -39,6 +39,7 @@ HAS_GOOGLE_AUTH_AIO = False import google.auth +import google.protobuf.duration_pb2 as duration_pb2 # type: ignore import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore import google.protobuf.timestamp_pb2 as timestamp_pb2 # type: ignore import google.protobuf.wrappers_pb2 as wrappers_pb2 # type: ignore @@ -68,6 +69,7 @@ action_status, annotation, attachment, + availability, contextual_addon, deletion_metadata, event_payload, @@ -88,6 +90,7 @@ user, widgets, ) +from google.apps.chat_v1.types import availability as gc_availability 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 @@ -1342,6 +1345,8 @@ def test_chat_service_client_create_channel_credentials_file( "https://www.googleapis.com/auth/chat.spaces", "https://www.googleapis.com/auth/chat.spaces.create", "https://www.googleapis.com/auth/chat.spaces.readonly", + "https://www.googleapis.com/auth/chat.users.availability", + "https://www.googleapis.com/auth/chat.users.availability.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", @@ -12553,11 +12558,11 @@ async def test_get_thread_read_state_flattened_error_async(): @pytest.mark.parametrize( "request_type", [ - space_event.GetSpaceEventRequest(), + availability.GetAvailabilityRequest(), {}, ], ) -def test_get_space_event(request_type, transport: str = "grpc"): +def test_get_availability(request_type, transport: str = "grpc"): client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -12568,27 +12573,27 @@ def test_get_space_event(request_type, transport: str = "grpc"): request = request_type # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_space_event), "__call__") as call: + with mock.patch.object(type(client.transport.get_availability), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = space_event.SpaceEvent( + call.return_value = availability.Availability( name="name_value", - event_type="event_type_value", + state=availability.Availability.State.ACTIVE, ) - response = client.get_space_event(request) + response = client.get_availability(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - request = space_event.GetSpaceEventRequest() + request = availability.GetAvailabilityRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, space_event.SpaceEvent) + assert isinstance(response, availability.Availability) assert response.name == "name_value" - assert response.event_type == "event_type_value" + assert response.state == availability.Availability.State.ACTIVE -def test_get_space_event_non_empty_request_with_auto_populated_field(): +def test_get_availability_non_empty_request_with_auto_populated_field(): # 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( @@ -12599,25 +12604,25 @@ def test_get_space_event_non_empty_request_with_auto_populated_field(): # Populate all string fields in the request which are not UUID4 # since we want to check that UUID4 are populated automatically # if they meet the requirements of AIP 4235. - request = space_event.GetSpaceEventRequest( + request = availability.GetAvailabilityRequest( name="name_value", ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_space_event), "__call__") as call: + with mock.patch.object(type(client.transport.get_availability), "__call__") as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.get_space_event(request=request) + client.get_availability(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - request_msg = space_event.GetSpaceEventRequest( + request_msg = availability.GetAvailabilityRequest( name="name_value", ) assert args[0] == request_msg -def test_get_space_event_use_cached_wrapped_rpc(): +def test_get_availability_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -12631,21 +12636,23 @@ def test_get_space_event_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.get_availability in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = 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.get_availability] = ( + mock_rpc + ) request = {} - client.get_space_event(request) + client.get_availability(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.get_space_event(request) + client.get_availability(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -12653,7 +12660,7 @@ def test_get_space_event_use_cached_wrapped_rpc(): @pytest.mark.asyncio -async def test_get_space_event_async_use_cached_wrapped_rpc( +async def test_get_availability_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", ): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, @@ -12670,7 +12677,7 @@ async def test_get_space_event_async_use_cached_wrapped_rpc( # Ensure method has been cached assert ( - client._client._transport.get_space_event + client._client._transport.get_availability in client._client._transport._wrapped_methods ) @@ -12678,16 +12685,16 @@ async def test_get_space_event_async_use_cached_wrapped_rpc( mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() client._client._transport._wrapped_methods[ - client._client._transport.get_space_event + client._client._transport.get_availability ] = mock_rpc request = {} - await client.get_space_event(request) + await client.get_availability(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - await client.get_space_event(request) + await client.get_availability(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -12698,11 +12705,11 @@ async def test_get_space_event_async_use_cached_wrapped_rpc( @pytest.mark.parametrize( "request_type", [ - space_event.GetSpaceEventRequest(), + availability.GetAvailabilityRequest(), {}, ], ) -async def test_get_space_event_async(request_type, transport: str = "grpc_asyncio"): +async def test_get_availability_async(request_type, transport: str = "grpc_asyncio"): client = ChatServiceAsyncClient( credentials=async_anonymous_credentials(), transport=transport, @@ -12713,43 +12720,43 @@ async def test_get_space_event_async(request_type, transport: str = "grpc_asynci request = request_type # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_space_event), "__call__") as call: + with mock.patch.object(type(client.transport.get_availability), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - space_event.SpaceEvent( + availability.Availability( name="name_value", - event_type="event_type_value", + state=availability.Availability.State.ACTIVE, ) ) - response = await client.get_space_event(request) + response = await client.get_availability(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request = space_event.GetSpaceEventRequest() + request = availability.GetAvailabilityRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, space_event.SpaceEvent) + assert isinstance(response, availability.Availability) assert response.name == "name_value" - assert response.event_type == "event_type_value" + assert response.state == availability.Availability.State.ACTIVE -def test_get_space_event_field_headers(): +def test_get_availability_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 = space_event.GetSpaceEventRequest() + request = availability.GetAvailabilityRequest() request.name = "name_value" # Mock the actual call within the gRPC stub, 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) + with mock.patch.object(type(client.transport.get_availability), "__call__") as call: + call.return_value = availability.Availability() + client.get_availability(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 @@ -12765,23 +12772,23 @@ def test_get_space_event_field_headers(): @pytest.mark.asyncio -async def test_get_space_event_field_headers_async(): +async def test_get_availability_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 = space_event.GetSpaceEventRequest() + request = availability.GetAvailabilityRequest() request.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_space_event), "__call__") as call: + with mock.patch.object(type(client.transport.get_availability), "__call__") as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - space_event.SpaceEvent() + availability.Availability() ) - await client.get_space_event(request) + await client.get_availability(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) @@ -12796,18 +12803,18 @@ async def test_get_space_event_field_headers_async(): ) in kw["metadata"] -def test_get_space_event_flattened(): +def test_get_availability_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.get_space_event), "__call__") as call: + with mock.patch.object(type(client.transport.get_availability), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = space_event.SpaceEvent() + call.return_value = availability.Availability() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - client.get_space_event( + client.get_availability( name="name_value", ) @@ -12820,7 +12827,7 @@ def test_get_space_event_flattened(): assert arg == mock_val -def test_get_space_event_flattened_error(): +def test_get_availability_flattened_error(): client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -12828,29 +12835,29 @@ def test_get_space_event_flattened_error(): # 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.get_availability( + availability.GetAvailabilityRequest(), name="name_value", ) @pytest.mark.asyncio -async def test_get_space_event_flattened_async(): +async def test_get_availability_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.get_space_event), "__call__") as call: + with mock.patch.object(type(client.transport.get_availability), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = space_event.SpaceEvent() + call.return_value = availability.Availability() call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - space_event.SpaceEvent() + availability.Availability() ) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - response = await client.get_space_event( + response = await client.get_availability( name="name_value", ) @@ -12864,7 +12871,7 @@ async def test_get_space_event_flattened_async(): @pytest.mark.asyncio -async def test_get_space_event_flattened_error_async(): +async def test_get_availability_flattened_error_async(): client = ChatServiceAsyncClient( credentials=async_anonymous_credentials(), ) @@ -12872,8 +12879,8 @@ async def test_get_space_event_flattened_error_async(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - await client.get_space_event( - space_event.GetSpaceEventRequest(), + await client.get_availability( + availability.GetAvailabilityRequest(), name="name_value", ) @@ -12881,11 +12888,11 @@ async def test_get_space_event_flattened_error_async(): @pytest.mark.parametrize( "request_type", [ - space_event.ListSpaceEventsRequest(), + availability.MarkAsActiveRequest(), {}, ], ) -def test_list_space_events(request_type, transport: str = "grpc"): +def test_mark_as_active(request_type, transport: str = "grpc"): client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -12896,27 +12903,27 @@ def test_list_space_events(request_type, transport: str = "grpc"): request = request_type # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_space_events), "__call__" - ) as call: + with mock.patch.object(type(client.transport.mark_as_active), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = space_event.ListSpaceEventsResponse( - next_page_token="next_page_token_value", + call.return_value = availability.Availability( + name="name_value", + state=availability.Availability.State.ACTIVE, ) - response = client.list_space_events(request) + response = client.mark_as_active(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - request = space_event.ListSpaceEventsRequest() + request = availability.MarkAsActiveRequest() assert args[0] == 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, availability.Availability) + assert response.name == "name_value" + assert response.state == availability.Availability.State.ACTIVE -def test_list_space_events_non_empty_request_with_auto_populated_field(): +def test_mark_as_active_non_empty_request_with_auto_populated_field(): # 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( @@ -12927,31 +12934,25 @@ def test_list_space_events_non_empty_request_with_auto_populated_field(): # Populate all string fields in the request which are not UUID4 # since we want to check that UUID4 are populated automatically # if they meet the requirements of AIP 4235. - request = space_event.ListSpaceEventsRequest( - parent="parent_value", - page_token="page_token_value", - filter="filter_value", + request = availability.MarkAsActiveRequest( + name="name_value", ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_space_events), "__call__" - ) as call: + with mock.patch.object(type(client.transport.mark_as_active), "__call__") as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.list_space_events(request=request) + client.mark_as_active(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - request_msg = space_event.ListSpaceEventsRequest( - parent="parent_value", - page_token="page_token_value", - filter="filter_value", + request_msg = availability.MarkAsActiveRequest( + name="name_value", ) assert args[0] == request_msg -def test_list_space_events_use_cached_wrapped_rpc(): +def test_mark_as_active_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -12965,23 +12966,21 @@ def test_list_space_events_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.mark_as_active in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = 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 - ) + client._transport._wrapped_methods[client._transport.mark_as_active] = mock_rpc request = {} - client.list_space_events(request) + client.mark_as_active(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.list_space_events(request) + client.mark_as_active(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -12989,7 +12988,7 @@ def test_list_space_events_use_cached_wrapped_rpc(): @pytest.mark.asyncio -async def test_list_space_events_async_use_cached_wrapped_rpc( +async def test_mark_as_active_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", ): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, @@ -13006,7 +13005,7 @@ async def test_list_space_events_async_use_cached_wrapped_rpc( # Ensure method has been cached assert ( - client._client._transport.list_space_events + client._client._transport.mark_as_active in client._client._transport._wrapped_methods ) @@ -13014,16 +13013,16 @@ async def test_list_space_events_async_use_cached_wrapped_rpc( mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() client._client._transport._wrapped_methods[ - client._client._transport.list_space_events + client._client._transport.mark_as_active ] = mock_rpc request = {} - await client.list_space_events(request) + await client.mark_as_active(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - await client.list_space_events(request) + await client.mark_as_active(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -13034,11 +13033,11 @@ async def test_list_space_events_async_use_cached_wrapped_rpc( @pytest.mark.parametrize( "request_type", [ - space_event.ListSpaceEventsRequest(), + availability.MarkAsActiveRequest(), {}, ], ) -async def test_list_space_events_async(request_type, transport: str = "grpc_asyncio"): +async def test_mark_as_active_async(request_type, transport: str = "grpc_asyncio"): client = ChatServiceAsyncClient( credentials=async_anonymous_credentials(), transport=transport, @@ -13049,45 +13048,43 @@ async def test_list_space_events_async(request_type, transport: str = "grpc_asyn request = request_type # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_space_events), "__call__" - ) as call: + with mock.patch.object(type(client.transport.mark_as_active), "__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", + availability.Availability( + name="name_value", + state=availability.Availability.State.ACTIVE, ) ) - response = await client.list_space_events(request) + response = await client.mark_as_active(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request = space_event.ListSpaceEventsRequest() + request = availability.MarkAsActiveRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListSpaceEventsAsyncPager) - assert response.next_page_token == "next_page_token_value" + assert isinstance(response, availability.Availability) + assert response.name == "name_value" + assert response.state == availability.Availability.State.ACTIVE -def test_list_space_events_field_headers(): +def test_mark_as_active_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 = space_event.ListSpaceEventsRequest() + request = availability.MarkAsActiveRequest() - request.parent = "parent_value" + request.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_space_events), "__call__" - ) as call: - call.return_value = space_event.ListSpaceEventsResponse() - client.list_space_events(request) + with mock.patch.object(type(client.transport.mark_as_active), "__call__") as call: + call.return_value = availability.Availability() + client.mark_as_active(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 @@ -13098,30 +13095,28 @@ def test_list_space_events_field_headers(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "parent=parent_value", + "name=name_value", ) in kw["metadata"] @pytest.mark.asyncio -async def test_list_space_events_field_headers_async(): +async def test_mark_as_active_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 = space_event.ListSpaceEventsRequest() + request = availability.MarkAsActiveRequest() - request.parent = "parent_value" + request.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_space_events), "__call__" - ) as call: + with mock.patch.object(type(client.transport.mark_as_active), "__call__") as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - space_event.ListSpaceEventsResponse() + availability.Availability() ) - await client.list_space_events(request) + await client.mark_as_active(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) @@ -13132,312 +13127,18 @@ async def test_list_space_events_field_headers_async(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "parent=parent_value", + "name=name_value", ) in kw["metadata"] -def test_list_space_events_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_space_events), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = space_event.ListSpaceEventsResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_space_events( - parent="parent_value", - filter="filter_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].filter - mock_val = "filter_value" - assert arg == mock_val - - -def test_list_space_events_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.list_space_events( - space_event.ListSpaceEventsRequest(), - parent="parent_value", - filter="filter_value", - ) - - -@pytest.mark.asyncio -async def test_list_space_events_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.list_space_events), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = space_event.ListSpaceEventsResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - space_event.ListSpaceEventsResponse() - ) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_space_events( - parent="parent_value", - filter="filter_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].filter - mock_val = "filter_value" - assert arg == mock_val - - -@pytest.mark.asyncio -async def test_list_space_events_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_space_events( - space_event.ListSpaceEventsRequest(), - parent="parent_value", - filter="filter_value", - ) - - -def test_list_space_events_pager(transport_name: str = "grpc"): - client = ChatServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport_name, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_space_events), "__call__" - ) as call: - # Set the response to a series of pages. - call.side_effect = ( - 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(), - ], - ), - RuntimeError, - ) - - expected_metadata = () - retry = retries.Retry() - timeout = 5 - expected_metadata = tuple(expected_metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)), - ) - pager = client.list_space_events(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, space_event.SpaceEvent) for i in results) - - -def test_list_space_events_pages(transport_name: str = "grpc"): - client = ChatServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport_name, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_space_events), "__call__" - ) as call: - # Set the response to a series of pages. - call.side_effect = ( - 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(), - ], - ), - RuntimeError, - ) - pages = list(client.list_space_events(request={}).pages) - for page_, token in zip(pages, ["abc", "def", "ghi", ""]): - assert page_.raw_page.next_page_token == token - - -@pytest.mark.asyncio -async def test_list_space_events_async_pager(): - 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.list_space_events), - "__call__", - new_callable=mock.AsyncMock, - ) as call: - # Set the response to a series of pages. - call.side_effect = ( - 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(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_space_events( - request={}, - ) - assert async_pager.next_page_token == "abc" - responses = [] - async for response in async_pager: # pragma: no branch - responses.append(response) - - assert len(responses) == 6 - assert all(isinstance(i, space_event.SpaceEvent) for i in responses) - - -@pytest.mark.asyncio -async def test_list_space_events_async_pages(): - 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.list_space_events), - "__call__", - new_callable=mock.AsyncMock, - ) as call: - # Set the response to a series of pages. - call.side_effect = ( - 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(), - ], - ), - RuntimeError, - ) - pages = [] - async for page_ in (await client.list_space_events(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", [ - space_notification_setting.GetSpaceNotificationSettingRequest(), + availability.MarkAsAwayRequest(), {}, ], ) -def test_get_space_notification_setting(request_type, transport: str = "grpc"): +def test_mark_as_away(request_type, transport: str = "grpc"): client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -13448,37 +13149,27 @@ def test_get_space_notification_setting(request_type, transport: str = "grpc"): request = request_type # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_space_notification_setting), "__call__" - ) as call: + with mock.patch.object(type(client.transport.mark_as_away), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = space_notification_setting.SpaceNotificationSetting( + call.return_value = availability.Availability( name="name_value", - notification_setting=space_notification_setting.SpaceNotificationSetting.NotificationSetting.ALL, - mute_setting=space_notification_setting.SpaceNotificationSetting.MuteSetting.UNMUTED, + state=availability.Availability.State.ACTIVE, ) - response = client.get_space_notification_setting(request) + response = client.mark_as_away(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - request = space_notification_setting.GetSpaceNotificationSettingRequest() + request = availability.MarkAsAwayRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, space_notification_setting.SpaceNotificationSetting) + assert isinstance(response, availability.Availability) 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 response.state == availability.Availability.State.ACTIVE -def test_get_space_notification_setting_non_empty_request_with_auto_populated_field(): +def test_mark_as_away_non_empty_request_with_auto_populated_field(): # 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( @@ -13489,27 +13180,25 @@ def test_get_space_notification_setting_non_empty_request_with_auto_populated_fi # Populate all string fields in the request which are not UUID4 # since we want to check that UUID4 are populated automatically # if they meet the requirements of AIP 4235. - request = space_notification_setting.GetSpaceNotificationSettingRequest( + request = availability.MarkAsAwayRequest( name="name_value", ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_space_notification_setting), "__call__" - ) as call: + with mock.patch.object(type(client.transport.mark_as_away), "__call__") as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.get_space_notification_setting(request=request) + client.mark_as_away(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - request_msg = space_notification_setting.GetSpaceNotificationSettingRequest( + request_msg = availability.MarkAsAwayRequest( name="name_value", ) assert args[0] == request_msg -def test_get_space_notification_setting_use_cached_wrapped_rpc(): +def test_mark_as_away_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -13523,26 +13212,21 @@ def test_get_space_notification_setting_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.mark_as_away in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = 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.mark_as_away] = mock_rpc request = {} - client.get_space_notification_setting(request) + client.mark_as_away(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.get_space_notification_setting(request) + client.mark_as_away(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -13550,7 +13234,7 @@ def test_get_space_notification_setting_use_cached_wrapped_rpc(): @pytest.mark.asyncio -async def test_get_space_notification_setting_async_use_cached_wrapped_rpc( +async def test_mark_as_away_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", ): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, @@ -13567,7 +13251,7 @@ async def test_get_space_notification_setting_async_use_cached_wrapped_rpc( # Ensure method has been cached assert ( - client._client._transport.get_space_notification_setting + client._client._transport.mark_as_away in client._client._transport._wrapped_methods ) @@ -13575,16 +13259,16 @@ async def test_get_space_notification_setting_async_use_cached_wrapped_rpc( mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() client._client._transport._wrapped_methods[ - client._client._transport.get_space_notification_setting + client._client._transport.mark_as_away ] = mock_rpc request = {} - await client.get_space_notification_setting(request) + await client.mark_as_away(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - await client.get_space_notification_setting(request) + await client.mark_as_away(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -13595,13 +13279,11 @@ async def test_get_space_notification_setting_async_use_cached_wrapped_rpc( @pytest.mark.parametrize( "request_type", [ - space_notification_setting.GetSpaceNotificationSettingRequest(), + availability.MarkAsAwayRequest(), {}, ], ) -async def test_get_space_notification_setting_async( - request_type, transport: str = "grpc_asyncio" -): +async def test_mark_as_away_async(request_type, transport: str = "grpc_asyncio"): client = ChatServiceAsyncClient( credentials=async_anonymous_credentials(), transport=transport, @@ -13612,55 +13294,43 @@ async def test_get_space_notification_setting_async( request = request_type # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_space_notification_setting), "__call__" - ) as call: + with mock.patch.object(type(client.transport.mark_as_away), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - space_notification_setting.SpaceNotificationSetting( + availability.Availability( name="name_value", - notification_setting=space_notification_setting.SpaceNotificationSetting.NotificationSetting.ALL, - mute_setting=space_notification_setting.SpaceNotificationSetting.MuteSetting.UNMUTED, + state=availability.Availability.State.ACTIVE, ) ) - response = await client.get_space_notification_setting(request) + response = await client.mark_as_away(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request = space_notification_setting.GetSpaceNotificationSettingRequest() + request = availability.MarkAsAwayRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, space_notification_setting.SpaceNotificationSetting) + assert isinstance(response, availability.Availability) 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 response.state == availability.Availability.State.ACTIVE -def test_get_space_notification_setting_field_headers(): +def test_mark_as_away_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 = space_notification_setting.GetSpaceNotificationSettingRequest() + request = availability.MarkAsAwayRequest() request.name = "name_value" # Mock the actual call within the gRPC stub, 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) + with mock.patch.object(type(client.transport.mark_as_away), "__call__") as call: + call.return_value = availability.Availability() + client.mark_as_away(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 @@ -13676,25 +13346,23 @@ def test_get_space_notification_setting_field_headers(): @pytest.mark.asyncio -async def test_get_space_notification_setting_field_headers_async(): +async def test_mark_as_away_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 = space_notification_setting.GetSpaceNotificationSettingRequest() + request = availability.MarkAsAwayRequest() request.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_space_notification_setting), "__call__" - ) as call: + with mock.patch.object(type(client.transport.mark_as_away), "__call__") as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - space_notification_setting.SpaceNotificationSetting() + availability.Availability() ) - await client.get_space_notification_setting(request) + await client.mark_as_away(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) @@ -13709,100 +13377,14 @@ async def test_get_space_notification_setting_field_headers_async(): ) in kw["metadata"] -def test_get_space_notification_setting_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.get_space_notification_setting), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = space_notification_setting.SpaceNotificationSetting() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_space_notification_setting( - name="name_value", - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = "name_value" - assert arg == mock_val - - -def test_get_space_notification_setting_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.get_space_notification_setting( - space_notification_setting.GetSpaceNotificationSettingRequest(), - name="name_value", - ) - - -@pytest.mark.asyncio -async def test_get_space_notification_setting_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.get_space_notification_setting), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = space_notification_setting.SpaceNotificationSetting() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - space_notification_setting.SpaceNotificationSetting() - ) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_space_notification_setting( - name="name_value", - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = "name_value" - assert arg == mock_val - - -@pytest.mark.asyncio -async def test_get_space_notification_setting_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.get_space_notification_setting( - space_notification_setting.GetSpaceNotificationSettingRequest(), - name="name_value", - ) - - -@pytest.mark.parametrize( - "request_type", - [ - gc_space_notification_setting.UpdateSpaceNotificationSettingRequest(), - {}, - ], -) -def test_update_space_notification_setting(request_type, transport: str = "grpc"): +@pytest.mark.parametrize( + "request_type", + [ + availability.MarkAsDoNotDisturbRequest(), + {}, + ], +) +def test_mark_as_do_not_disturb(request_type, transport: str = "grpc"): client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -13814,36 +13396,28 @@ def test_update_space_notification_setting(request_type, transport: str = "grpc" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_space_notification_setting), "__call__" + type(client.transport.mark_as_do_not_disturb), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = gc_space_notification_setting.SpaceNotificationSetting( + call.return_value = availability.Availability( name="name_value", - notification_setting=gc_space_notification_setting.SpaceNotificationSetting.NotificationSetting.ALL, - mute_setting=gc_space_notification_setting.SpaceNotificationSetting.MuteSetting.UNMUTED, + state=availability.Availability.State.ACTIVE, ) - response = client.update_space_notification_setting(request) + response = client.mark_as_do_not_disturb(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - request = gc_space_notification_setting.UpdateSpaceNotificationSettingRequest() + request = availability.MarkAsDoNotDisturbRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, gc_space_notification_setting.SpaceNotificationSetting) + assert isinstance(response, availability.Availability) 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 response.state == availability.Availability.State.ACTIVE -def test_update_space_notification_setting_non_empty_request_with_auto_populated_field(): +def test_mark_as_do_not_disturb_non_empty_request_with_auto_populated_field(): # 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( @@ -13854,25 +13428,27 @@ def test_update_space_notification_setting_non_empty_request_with_auto_populated # Populate all string fields in the request which are not UUID4 # since we want to check that UUID4 are populated automatically # if they meet the requirements of AIP 4235. - request = gc_space_notification_setting.UpdateSpaceNotificationSettingRequest() + request = availability.MarkAsDoNotDisturbRequest( + name="name_value", + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_space_notification_setting), "__call__" + type(client.transport.mark_as_do_not_disturb), "__call__" ) as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.update_space_notification_setting(request=request) + client.mark_as_do_not_disturb(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - request_msg = ( - gc_space_notification_setting.UpdateSpaceNotificationSettingRequest() + request_msg = availability.MarkAsDoNotDisturbRequest( + name="name_value", ) assert args[0] == request_msg -def test_update_space_notification_setting_use_cached_wrapped_rpc(): +def test_mark_as_do_not_disturb_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -13887,7 +13463,7 @@ def test_update_space_notification_setting_use_cached_wrapped_rpc(): # Ensure method has been cached assert ( - client._transport.update_space_notification_setting + client._transport.mark_as_do_not_disturb in client._transport._wrapped_methods ) @@ -13896,16 +13472,16 @@ def test_update_space_notification_setting_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.mark_as_do_not_disturb] = ( + mock_rpc + ) request = {} - client.update_space_notification_setting(request) + client.mark_as_do_not_disturb(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.update_space_notification_setting(request) + client.mark_as_do_not_disturb(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -13913,7 +13489,7 @@ def test_update_space_notification_setting_use_cached_wrapped_rpc(): @pytest.mark.asyncio -async def test_update_space_notification_setting_async_use_cached_wrapped_rpc( +async def test_mark_as_do_not_disturb_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", ): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, @@ -13930,7 +13506,7 @@ async def test_update_space_notification_setting_async_use_cached_wrapped_rpc( # Ensure method has been cached assert ( - client._client._transport.update_space_notification_setting + client._client._transport.mark_as_do_not_disturb in client._client._transport._wrapped_methods ) @@ -13938,16 +13514,16 @@ async def test_update_space_notification_setting_async_use_cached_wrapped_rpc( mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() client._client._transport._wrapped_methods[ - client._client._transport.update_space_notification_setting + client._client._transport.mark_as_do_not_disturb ] = mock_rpc request = {} - await client.update_space_notification_setting(request) + await client.mark_as_do_not_disturb(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - await client.update_space_notification_setting(request) + await client.mark_as_do_not_disturb(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -13958,11 +13534,11 @@ async def test_update_space_notification_setting_async_use_cached_wrapped_rpc( @pytest.mark.parametrize( "request_type", [ - gc_space_notification_setting.UpdateSpaceNotificationSettingRequest(), + availability.MarkAsDoNotDisturbRequest(), {}, ], ) -async def test_update_space_notification_setting_async( +async def test_mark_as_do_not_disturb_async( request_type, transport: str = "grpc_asyncio" ): client = ChatServiceAsyncClient( @@ -13976,54 +13552,46 @@ async def test_update_space_notification_setting_async( # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_space_notification_setting), "__call__" + type(client.transport.mark_as_do_not_disturb), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - gc_space_notification_setting.SpaceNotificationSetting( + availability.Availability( name="name_value", - notification_setting=gc_space_notification_setting.SpaceNotificationSetting.NotificationSetting.ALL, - mute_setting=gc_space_notification_setting.SpaceNotificationSetting.MuteSetting.UNMUTED, + state=availability.Availability.State.ACTIVE, ) ) - response = await client.update_space_notification_setting(request) + response = await client.mark_as_do_not_disturb(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request = gc_space_notification_setting.UpdateSpaceNotificationSettingRequest() + request = availability.MarkAsDoNotDisturbRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, gc_space_notification_setting.SpaceNotificationSetting) + assert isinstance(response, availability.Availability) 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 response.state == availability.Availability.State.ACTIVE -def test_update_space_notification_setting_field_headers(): +def test_mark_as_do_not_disturb_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 = gc_space_notification_setting.UpdateSpaceNotificationSettingRequest() + request = availability.MarkAsDoNotDisturbRequest() - request.space_notification_setting.name = "name_value" + request.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_space_notification_setting), "__call__" + type(client.transport.mark_as_do_not_disturb), "__call__" ) as call: - call.return_value = gc_space_notification_setting.SpaceNotificationSetting() - client.update_space_notification_setting(request) + call.return_value = availability.Availability() + client.mark_as_do_not_disturb(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 @@ -14034,30 +13602,30 @@ def test_update_space_notification_setting_field_headers(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "space_notification_setting.name=name_value", + "name=name_value", ) in kw["metadata"] @pytest.mark.asyncio -async def test_update_space_notification_setting_field_headers_async(): +async def test_mark_as_do_not_disturb_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 = gc_space_notification_setting.UpdateSpaceNotificationSettingRequest() + request = availability.MarkAsDoNotDisturbRequest() - request.space_notification_setting.name = "name_value" + request.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_space_notification_setting), "__call__" + type(client.transport.mark_as_do_not_disturb), "__call__" ) as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - gc_space_notification_setting.SpaceNotificationSetting() + availability.Availability() ) - await client.update_space_notification_setting(request) + await client.mark_as_do_not_disturb(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) @@ -14068,126 +13636,18 @@ async def test_update_space_notification_setting_field_headers_async(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "space_notification_setting.name=name_value", + "name=name_value", ) in kw["metadata"] -def test_update_space_notification_setting_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.update_space_notification_setting), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = gc_space_notification_setting.SpaceNotificationSetting() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.update_space_notification_setting( - space_notification_setting=gc_space_notification_setting.SpaceNotificationSetting( - name="name_value" - ), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].space_notification_setting - mock_val = gc_space_notification_setting.SpaceNotificationSetting( - name="name_value" - ) - assert arg == mock_val - arg = args[0].update_mask - mock_val = field_mask_pb2.FieldMask(paths=["paths_value"]) - assert arg == mock_val - - -def test_update_space_notification_setting_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.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"]), - ) - - -@pytest.mark.asyncio -async def test_update_space_notification_setting_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.update_space_notification_setting), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = gc_space_notification_setting.SpaceNotificationSetting() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - gc_space_notification_setting.SpaceNotificationSetting() - ) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.update_space_notification_setting( - space_notification_setting=gc_space_notification_setting.SpaceNotificationSetting( - name="name_value" - ), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].space_notification_setting - mock_val = gc_space_notification_setting.SpaceNotificationSetting( - name="name_value" - ) - assert arg == mock_val - arg = args[0].update_mask - mock_val = field_mask_pb2.FieldMask(paths=["paths_value"]) - assert arg == mock_val - - -@pytest.mark.asyncio -async def test_update_space_notification_setting_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.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"]), - ) - - @pytest.mark.parametrize( "request_type", [ - gc_section.CreateSectionRequest(), + gc_availability.UpdateAvailabilityRequest(), {}, ], ) -def test_create_section(request_type, transport: str = "grpc"): +def test_update_availability(request_type, transport: str = "grpc"): client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -14198,31 +13658,29 @@ def test_create_section(request_type, transport: str = "grpc"): request = request_type # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.create_section), "__call__") as call: + with mock.patch.object( + type(client.transport.update_availability), "__call__" + ) as call: # Designate an appropriate return value for the call. - call.return_value = gc_section.Section( + call.return_value = gc_availability.Availability( name="name_value", - display_name="display_name_value", - sort_order=1091, - type_=gc_section.Section.SectionType.CUSTOM_SECTION, + state=gc_availability.Availability.State.ACTIVE, ) - response = client.create_section(request) + response = client.update_availability(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() + request = gc_availability.UpdateAvailabilityRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, gc_section.Section) + assert isinstance(response, gc_availability.Availability) 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 + assert response.state == gc_availability.Availability.State.ACTIVE -def test_create_section_non_empty_request_with_auto_populated_field(): +def test_update_availability_non_empty_request_with_auto_populated_field(): # 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( @@ -14233,25 +13691,23 @@ def test_create_section_non_empty_request_with_auto_populated_field(): # Populate all string fields in the request which are not UUID4 # since we want to check that UUID4 are populated automatically # if they meet the requirements of AIP 4235. - request = gc_section.CreateSectionRequest( - parent="parent_value", - ) + request = gc_availability.UpdateAvailabilityRequest() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.create_section), "__call__") as call: + with mock.patch.object( + type(client.transport.update_availability), "__call__" + ) as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.create_section(request=request) + client.update_availability(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - request_msg = gc_section.CreateSectionRequest( - parent="parent_value", - ) + request_msg = gc_availability.UpdateAvailabilityRequest() assert args[0] == request_msg -def test_create_section_use_cached_wrapped_rpc(): +def test_update_availability_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -14265,21 +13721,25 @@ def test_create_section_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.create_section in client._transport._wrapped_methods + assert ( + client._transport.update_availability in client._transport._wrapped_methods + ) # Replace cached wrapped function with mock mock_rpc = 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_section] = mock_rpc + client._transport._wrapped_methods[client._transport.update_availability] = ( + mock_rpc + ) request = {} - client.create_section(request) + client.update_availability(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.create_section(request) + client.update_availability(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -14287,7 +13747,7 @@ def test_create_section_use_cached_wrapped_rpc(): @pytest.mark.asyncio -async def test_create_section_async_use_cached_wrapped_rpc( +async def test_update_availability_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", ): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, @@ -14304,7 +13764,7 @@ async def test_create_section_async_use_cached_wrapped_rpc( # Ensure method has been cached assert ( - client._client._transport.create_section + client._client._transport.update_availability in client._client._transport._wrapped_methods ) @@ -14312,16 +13772,16 @@ async def test_create_section_async_use_cached_wrapped_rpc( mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() client._client._transport._wrapped_methods[ - client._client._transport.create_section + client._client._transport.update_availability ] = mock_rpc request = {} - await client.create_section(request) + await client.update_availability(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - await client.create_section(request) + await client.update_availability(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -14332,11 +13792,11 @@ async def test_create_section_async_use_cached_wrapped_rpc( @pytest.mark.parametrize( "request_type", [ - gc_section.CreateSectionRequest(), + gc_availability.UpdateAvailabilityRequest(), {}, ], ) -async def test_create_section_async(request_type, transport: str = "grpc_asyncio"): +async def test_update_availability_async(request_type, transport: str = "grpc_asyncio"): client = ChatServiceAsyncClient( credentials=async_anonymous_credentials(), transport=transport, @@ -14347,47 +13807,47 @@ async def test_create_section_async(request_type, transport: str = "grpc_asyncio request = request_type # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.create_section), "__call__") as call: + with mock.patch.object( + type(client.transport.update_availability), "__call__" + ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - gc_section.Section( + gc_availability.Availability( name="name_value", - display_name="display_name_value", - sort_order=1091, - type_=gc_section.Section.SectionType.CUSTOM_SECTION, + state=gc_availability.Availability.State.ACTIVE, ) ) - response = await client.create_section(request) + response = await client.update_availability(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request = gc_section.CreateSectionRequest() + request = gc_availability.UpdateAvailabilityRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, gc_section.Section) + assert isinstance(response, gc_availability.Availability) 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 + assert response.state == gc_availability.Availability.State.ACTIVE -def test_create_section_field_headers(): +def test_update_availability_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 = gc_section.CreateSectionRequest() + request = gc_availability.UpdateAvailabilityRequest() - request.parent = "parent_value" + request.availability.name = "name_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 = gc_section.Section() - client.create_section(request) + with mock.patch.object( + type(client.transport.update_availability), "__call__" + ) as call: + call.return_value = gc_availability.Availability() + client.update_availability(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 @@ -14398,26 +13858,30 @@ def test_create_section_field_headers(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "parent=parent_value", + "availability.name=name_value", ) in kw["metadata"] @pytest.mark.asyncio -async def test_create_section_field_headers_async(): +async def test_update_availability_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 = gc_section.CreateSectionRequest() + request = gc_availability.UpdateAvailabilityRequest() - request.parent = "parent_value" + request.availability.name = "name_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) + with mock.patch.object( + type(client.transport.update_availability), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gc_availability.Availability() + ) + await client.update_availability(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) @@ -14428,39 +13892,41 @@ async def test_create_section_field_headers_async(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "parent=parent_value", + "availability.name=name_value", ) in kw["metadata"] -def test_create_section_flattened(): +def test_update_availability_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: + with mock.patch.object( + type(client.transport.update_availability), "__call__" + ) as call: # Designate an appropriate return value for the call. - call.return_value = gc_section.Section() + call.return_value = gc_availability.Availability() # 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"), + client.update_availability( + availability=gc_availability.Availability(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) # Establish that the underlying call was made with the expected # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - arg = args[0].parent - mock_val = "parent_value" + arg = args[0].availability + mock_val = gc_availability.Availability(name="name_value") assert arg == mock_val - arg = args[0].section - mock_val = gc_section.Section(name="name_value") + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=["paths_value"]) assert arg == mock_val -def test_create_section_flattened_error(): +def test_update_availability_flattened_error(): client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -14468,46 +13934,50 @@ def test_create_section_flattened_error(): # 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"), + client.update_availability( + gc_availability.UpdateAvailabilityRequest(), + availability=gc_availability.Availability(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) @pytest.mark.asyncio -async def test_create_section_flattened_async(): +async def test_update_availability_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: + with mock.patch.object( + type(client.transport.update_availability), "__call__" + ) as call: # Designate an appropriate return value for the call. - call.return_value = gc_section.Section() + call.return_value = gc_availability.Availability() - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gc_section.Section()) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gc_availability.Availability() + ) # 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"), + response = await client.update_availability( + availability=gc_availability.Availability(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) # Establish that the underlying call was made with the expected # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - arg = args[0].parent - mock_val = "parent_value" + arg = args[0].availability + mock_val = gc_availability.Availability(name="name_value") assert arg == mock_val - arg = args[0].section - mock_val = gc_section.Section(name="name_value") + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=["paths_value"]) assert arg == mock_val @pytest.mark.asyncio -async def test_create_section_flattened_error_async(): +async def test_update_availability_flattened_error_async(): client = ChatServiceAsyncClient( credentials=async_anonymous_credentials(), ) @@ -14515,21 +13985,21 @@ async def test_create_section_flattened_error_async(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - await client.create_section( - gc_section.CreateSectionRequest(), - parent="parent_value", - section=gc_section.Section(name="name_value"), + await client.update_availability( + gc_availability.UpdateAvailabilityRequest(), + availability=gc_availability.Availability(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) @pytest.mark.parametrize( "request_type", [ - section.DeleteSectionRequest(), + space_event.GetSpaceEventRequest(), {}, ], ) -def test_delete_section(request_type, transport: str = "grpc"): +def test_get_space_event(request_type, transport: str = "grpc"): client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -14540,22 +14010,27 @@ def test_delete_section(request_type, transport: str = "grpc"): request = request_type # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.delete_section), "__call__") as call: + with mock.patch.object(type(client.transport.get_space_event), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = None - response = client.delete_section(request) + call.return_value = space_event.SpaceEvent( + name="name_value", + event_type="event_type_value", + ) + response = client.get_space_event(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - request = section.DeleteSectionRequest() + request = space_event.GetSpaceEventRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert response is None + assert isinstance(response, space_event.SpaceEvent) + assert response.name == "name_value" + assert response.event_type == "event_type_value" -def test_delete_section_non_empty_request_with_auto_populated_field(): +def test_get_space_event_non_empty_request_with_auto_populated_field(): # 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( @@ -14566,25 +14041,25 @@ def test_delete_section_non_empty_request_with_auto_populated_field(): # Populate all string fields in the request which are not UUID4 # since we want to check that UUID4 are populated automatically # if they meet the requirements of AIP 4235. - request = section.DeleteSectionRequest( + request = space_event.GetSpaceEventRequest( 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: + with mock.patch.object(type(client.transport.get_space_event), "__call__") as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.delete_section(request=request) + client.get_space_event(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - request_msg = section.DeleteSectionRequest( + request_msg = space_event.GetSpaceEventRequest( name="name_value", ) assert args[0] == request_msg -def test_delete_section_use_cached_wrapped_rpc(): +def test_get_space_event_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -14598,21 +14073,21 @@ def test_delete_section_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.delete_section in client._transport._wrapped_methods + assert client._transport.get_space_event in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = 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 + client._transport._wrapped_methods[client._transport.get_space_event] = mock_rpc request = {} - client.delete_section(request) + client.get_space_event(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.delete_section(request) + client.get_space_event(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -14620,7 +14095,7 @@ def test_delete_section_use_cached_wrapped_rpc(): @pytest.mark.asyncio -async def test_delete_section_async_use_cached_wrapped_rpc( +async def test_get_space_event_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", ): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, @@ -14637,7 +14112,7 @@ async def test_delete_section_async_use_cached_wrapped_rpc( # Ensure method has been cached assert ( - client._client._transport.delete_section + client._client._transport.get_space_event in client._client._transport._wrapped_methods ) @@ -14645,16 +14120,16 @@ async def test_delete_section_async_use_cached_wrapped_rpc( mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() client._client._transport._wrapped_methods[ - client._client._transport.delete_section + client._client._transport.get_space_event ] = mock_rpc request = {} - await client.delete_section(request) + await client.get_space_event(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - await client.delete_section(request) + await client.get_space_event(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -14665,11 +14140,11 @@ async def test_delete_section_async_use_cached_wrapped_rpc( @pytest.mark.parametrize( "request_type", [ - section.DeleteSectionRequest(), + space_event.GetSpaceEventRequest(), {}, ], ) -async def test_delete_section_async(request_type, transport: str = "grpc_asyncio"): +async def test_get_space_event_async(request_type, transport: str = "grpc_asyncio"): client = ChatServiceAsyncClient( credentials=async_anonymous_credentials(), transport=transport, @@ -14680,36 +14155,43 @@ async def test_delete_section_async(request_type, transport: str = "grpc_asyncio request = request_type # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.delete_section), "__call__") as call: + 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(None) - response = await client.delete_section(request) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + space_event.SpaceEvent( + name="name_value", + event_type="event_type_value", + ) + ) + response = await client.get_space_event(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request = section.DeleteSectionRequest() + request = space_event.GetSpaceEventRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert response is None + assert isinstance(response, space_event.SpaceEvent) + assert response.name == "name_value" + assert response.event_type == "event_type_value" -def test_delete_section_field_headers(): +def test_get_space_event_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.DeleteSectionRequest() + request = space_event.GetSpaceEventRequest() 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) + with mock.patch.object(type(client.transport.get_space_event), "__call__") as call: + call.return_value = space_event.SpaceEvent() + client.get_space_event(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 @@ -14725,21 +14207,23 @@ def test_delete_section_field_headers(): @pytest.mark.asyncio -async def test_delete_section_field_headers_async(): +async def test_get_space_event_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 = space_event.GetSpaceEventRequest() 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 = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.delete_section(request) + with mock.patch.object(type(client.transport.get_space_event), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + space_event.SpaceEvent() + ) + await client.get_space_event(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) @@ -14754,18 +14238,18 @@ async def test_delete_section_field_headers_async(): ) in kw["metadata"] -def test_delete_section_flattened(): +def test_get_space_event_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.delete_section), "__call__") as call: + with mock.patch.object(type(client.transport.get_space_event), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = None + call.return_value = space_event.SpaceEvent() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - client.delete_section( + client.get_space_event( name="name_value", ) @@ -14778,7 +14262,7 @@ def test_delete_section_flattened(): assert arg == mock_val -def test_delete_section_flattened_error(): +def test_get_space_event_flattened_error(): client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -14786,27 +14270,29 @@ def test_delete_section_flattened_error(): # 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(), + client.get_space_event( + space_event.GetSpaceEventRequest(), name="name_value", ) @pytest.mark.asyncio -async def test_delete_section_flattened_async(): +async def test_get_space_event_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: + with mock.patch.object(type(client.transport.get_space_event), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = None + call.return_value = space_event.SpaceEvent() - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + space_event.SpaceEvent() + ) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - response = await client.delete_section( + response = await client.get_space_event( name="name_value", ) @@ -14820,7 +14306,7 @@ async def test_delete_section_flattened_async(): @pytest.mark.asyncio -async def test_delete_section_flattened_error_async(): +async def test_get_space_event_flattened_error_async(): client = ChatServiceAsyncClient( credentials=async_anonymous_credentials(), ) @@ -14828,8 +14314,8 @@ async def test_delete_section_flattened_error_async(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - await client.delete_section( - section.DeleteSectionRequest(), + await client.get_space_event( + space_event.GetSpaceEventRequest(), name="name_value", ) @@ -14837,11 +14323,11 @@ async def test_delete_section_flattened_error_async(): @pytest.mark.parametrize( "request_type", [ - gc_section.UpdateSectionRequest(), + space_event.ListSpaceEventsRequest(), {}, ], ) -def test_update_section(request_type, transport: str = "grpc"): +def test_list_space_events(request_type, transport: str = "grpc"): client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -14852,31 +14338,27 @@ def test_update_section(request_type, transport: str = "grpc"): request = request_type # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.update_section), "__call__") as call: + with mock.patch.object( + type(client.transport.list_space_events), "__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, + call.return_value = space_event.ListSpaceEventsResponse( + next_page_token="next_page_token_value", ) - response = client.update_section(request) + response = client.list_space_events(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - request = gc_section.UpdateSectionRequest() + request = space_event.ListSpaceEventsRequest() 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 + assert isinstance(response, pagers.ListSpaceEventsPager) + assert response.next_page_token == "next_page_token_value" -def test_update_section_non_empty_request_with_auto_populated_field(): +def test_list_space_events_non_empty_request_with_auto_populated_field(): # 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( @@ -14887,21 +14369,31 @@ def test_update_section_non_empty_request_with_auto_populated_field(): # Populate all string fields in the request which are not UUID4 # since we want to check that UUID4 are populated automatically # if they meet the requirements of AIP 4235. - request = gc_section.UpdateSectionRequest() + request = space_event.ListSpaceEventsRequest( + parent="parent_value", + page_token="page_token_value", + filter="filter_value", + ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.update_section), "__call__") as call: + with mock.patch.object( + type(client.transport.list_space_events), "__call__" + ) as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.update_section(request=request) + client.list_space_events(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - request_msg = gc_section.UpdateSectionRequest() + request_msg = space_event.ListSpaceEventsRequest( + parent="parent_value", + page_token="page_token_value", + filter="filter_value", + ) assert args[0] == request_msg -def test_update_section_use_cached_wrapped_rpc(): +def test_list_space_events_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -14915,21 +14407,23 @@ def test_update_section_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.update_section in client._transport._wrapped_methods + assert client._transport.list_space_events in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = 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_section] = mock_rpc + client._transport._wrapped_methods[client._transport.list_space_events] = ( + mock_rpc + ) request = {} - client.update_section(request) + client.list_space_events(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.update_section(request) + client.list_space_events(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -14937,7 +14431,7 @@ def test_update_section_use_cached_wrapped_rpc(): @pytest.mark.asyncio -async def test_update_section_async_use_cached_wrapped_rpc( +async def test_list_space_events_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", ): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, @@ -14954,7 +14448,7 @@ async def test_update_section_async_use_cached_wrapped_rpc( # Ensure method has been cached assert ( - client._client._transport.update_section + client._client._transport.list_space_events in client._client._transport._wrapped_methods ) @@ -14962,16 +14456,16 @@ async def test_update_section_async_use_cached_wrapped_rpc( mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() client._client._transport._wrapped_methods[ - client._client._transport.update_section + client._client._transport.list_space_events ] = mock_rpc request = {} - await client.update_section(request) + await client.list_space_events(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - await client.update_section(request) + await client.list_space_events(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -14982,11 +14476,11 @@ async def test_update_section_async_use_cached_wrapped_rpc( @pytest.mark.parametrize( "request_type", [ - gc_section.UpdateSectionRequest(), + space_event.ListSpaceEventsRequest(), {}, ], ) -async def test_update_section_async(request_type, transport: str = "grpc_asyncio"): +async def test_list_space_events_async(request_type, transport: str = "grpc_asyncio"): client = ChatServiceAsyncClient( credentials=async_anonymous_credentials(), transport=transport, @@ -14997,47 +14491,45 @@ async def test_update_section_async(request_type, transport: str = "grpc_asyncio request = request_type # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.update_section), "__call__") as call: + 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( - gc_section.Section( - name="name_value", - display_name="display_name_value", - sort_order=1091, - type_=gc_section.Section.SectionType.CUSTOM_SECTION, + space_event.ListSpaceEventsResponse( + next_page_token="next_page_token_value", ) ) - response = await client.update_section(request) + response = await client.list_space_events(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request = gc_section.UpdateSectionRequest() + request = space_event.ListSpaceEventsRequest() 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 + assert isinstance(response, pagers.ListSpaceEventsAsyncPager) + assert response.next_page_token == "next_page_token_value" -def test_update_section_field_headers(): +def test_list_space_events_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 = gc_section.UpdateSectionRequest() + request = space_event.ListSpaceEventsRequest() - request.section.name = "name_value" + request.parent = "parent_value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.update_section), "__call__") as call: - call.return_value = gc_section.Section() - client.update_section(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) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 @@ -15048,26 +14540,30 @@ def test_update_section_field_headers(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "section.name=name_value", + "parent=parent_value", ) in kw["metadata"] @pytest.mark.asyncio -async def test_update_section_field_headers_async(): +async def test_list_space_events_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 = gc_section.UpdateSectionRequest() + request = space_event.ListSpaceEventsRequest() - request.section.name = "name_value" + request.parent = "parent_value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.update_section), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gc_section.Section()) - await client.update_section(request) + with mock.patch.object( + type(client.transport.list_space_events), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + space_event.ListSpaceEventsResponse() + ) + await client.list_space_events(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) @@ -15078,39 +14574,41 @@ async def test_update_section_field_headers_async(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "section.name=name_value", + "parent=parent_value", ) in kw["metadata"] -def test_update_section_flattened(): +def test_list_space_events_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.update_section), "__call__") as call: + with mock.patch.object( + type(client.transport.list_space_events), "__call__" + ) as call: # Designate an appropriate return value for the call. - call.return_value = gc_section.Section() + call.return_value = space_event.ListSpaceEventsResponse() # 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"]), + client.list_space_events( + parent="parent_value", + filter="filter_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].section - mock_val = gc_section.Section(name="name_value") + arg = args[0].parent + mock_val = "parent_value" assert arg == mock_val - arg = args[0].update_mask - mock_val = field_mask_pb2.FieldMask(paths=["paths_value"]) + arg = args[0].filter + mock_val = "filter_value" assert arg == mock_val -def test_update_section_flattened_error(): +def test_list_space_events_flattened_error(): client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -15118,46 +14616,50 @@ def test_update_section_flattened_error(): # 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"]), + client.list_space_events( + space_event.ListSpaceEventsRequest(), + parent="parent_value", + filter="filter_value", ) @pytest.mark.asyncio -async def test_update_section_flattened_async(): +async def test_list_space_events_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.update_section), "__call__") as call: + with mock.patch.object( + type(client.transport.list_space_events), "__call__" + ) as call: # Designate an appropriate return value for the call. - call.return_value = gc_section.Section() + call.return_value = space_event.ListSpaceEventsResponse() - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gc_section.Section()) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + space_event.ListSpaceEventsResponse() + ) # 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"]), + response = await client.list_space_events( + parent="parent_value", + filter="filter_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].section - mock_val = gc_section.Section(name="name_value") + arg = args[0].parent + mock_val = "parent_value" assert arg == mock_val - arg = args[0].update_mask - mock_val = field_mask_pb2.FieldMask(paths=["paths_value"]) + arg = args[0].filter + mock_val = "filter_value" assert arg == mock_val @pytest.mark.asyncio -async def test_update_section_flattened_error_async(): +async def test_list_space_events_flattened_error_async(): client = ChatServiceAsyncClient( credentials=async_anonymous_credentials(), ) @@ -15165,21 +14667,219 @@ async def test_update_section_flattened_error_async(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - await client.update_section( - gc_section.UpdateSectionRequest(), - section=gc_section.Section(name="name_value"), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + await client.list_space_events( + space_event.ListSpaceEventsRequest(), + parent="parent_value", + filter="filter_value", + ) + + +def test_list_space_events_pager(transport_name: str = "grpc"): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_space_events), "__call__" + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + 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(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)), + ) + pager = client.list_space_events(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, space_event.SpaceEvent) for i in results) + + +def test_list_space_events_pages(transport_name: str = "grpc"): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_space_events), "__call__" + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + 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(), + ], + ), + RuntimeError, + ) + pages = list(client.list_space_events(request={}).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.asyncio +async def test_list_space_events_async_pager(): + 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.list_space_events), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + 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(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_space_events( + request={}, + ) + assert async_pager.next_page_token == "abc" + responses = [] + async for response in async_pager: # pragma: no branch + responses.append(response) + + assert len(responses) == 6 + assert all(isinstance(i, space_event.SpaceEvent) for i in responses) + + +@pytest.mark.asyncio +async def test_list_space_events_async_pages(): + 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.list_space_events), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + 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(), + ], + ), + RuntimeError, ) + pages = [] + async for page_ in (await client.list_space_events(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.ListSectionsRequest(), + space_notification_setting.GetSpaceNotificationSettingRequest(), {}, ], ) -def test_list_sections(request_type, transport: str = "grpc"): +def test_get_space_notification_setting(request_type, transport: str = "grpc"): client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -15190,25 +14890,37 @@ def test_list_sections(request_type, transport: str = "grpc"): request = request_type # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_sections), "__call__") as call: + 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 = section.ListSectionsResponse( - next_page_token="next_page_token_value", + call.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, ) - response = client.list_sections(request) + response = client.get_space_notification_setting(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - request = section.ListSectionsRequest() + request = space_notification_setting.GetSpaceNotificationSettingRequest() assert args[0] == 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" + 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 + ) -def test_list_sections_non_empty_request_with_auto_populated_field(): +def test_get_space_notification_setting_non_empty_request_with_auto_populated_field(): # 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( @@ -15219,27 +14931,27 @@ def test_list_sections_non_empty_request_with_auto_populated_field(): # Populate all string fields in the request which are not UUID4 # since we want to check that UUID4 are populated automatically # if they meet the requirements of AIP 4235. - request = section.ListSectionsRequest( - parent="parent_value", - page_token="page_token_value", + request = space_notification_setting.GetSpaceNotificationSettingRequest( + name="name_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: + with mock.patch.object( + type(client.transport.get_space_notification_setting), "__call__" + ) as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.list_sections(request=request) + client.get_space_notification_setting(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - request_msg = section.ListSectionsRequest( - parent="parent_value", - page_token="page_token_value", + request_msg = space_notification_setting.GetSpaceNotificationSettingRequest( + name="name_value", ) assert args[0] == request_msg -def test_list_sections_use_cached_wrapped_rpc(): +def test_get_space_notification_setting_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -15253,21 +14965,26 @@ def test_list_sections_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.list_sections in client._transport._wrapped_methods + assert ( + client._transport.get_space_notification_setting + in client._transport._wrapped_methods + ) # Replace cached wrapped function with mock mock_rpc = 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 + client._transport._wrapped_methods[ + client._transport.get_space_notification_setting + ] = mock_rpc request = {} - client.list_sections(request) + client.get_space_notification_setting(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.list_sections(request) + client.get_space_notification_setting(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -15275,7 +14992,7 @@ def test_list_sections_use_cached_wrapped_rpc(): @pytest.mark.asyncio -async def test_list_sections_async_use_cached_wrapped_rpc( +async def test_get_space_notification_setting_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", ): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, @@ -15292,7 +15009,7 @@ async def test_list_sections_async_use_cached_wrapped_rpc( # Ensure method has been cached assert ( - client._client._transport.list_sections + client._client._transport.get_space_notification_setting in client._client._transport._wrapped_methods ) @@ -15300,16 +15017,16 @@ async def test_list_sections_async_use_cached_wrapped_rpc( mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() client._client._transport._wrapped_methods[ - client._client._transport.list_sections + client._client._transport.get_space_notification_setting ] = mock_rpc request = {} - await client.list_sections(request) + await client.get_space_notification_setting(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - await client.list_sections(request) + await client.get_space_notification_setting(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -15320,11 +15037,13 @@ async def test_list_sections_async_use_cached_wrapped_rpc( @pytest.mark.parametrize( "request_type", [ - section.ListSectionsRequest(), + space_notification_setting.GetSpaceNotificationSettingRequest(), {}, ], ) -async def test_list_sections_async(request_type, transport: str = "grpc_asyncio"): +async def test_get_space_notification_setting_async( + request_type, transport: str = "grpc_asyncio" +): client = ChatServiceAsyncClient( credentials=async_anonymous_credentials(), transport=transport, @@ -15335,41 +15054,55 @@ async def test_list_sections_async(request_type, transport: str = "grpc_asyncio" request = request_type # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_sections), "__call__") as call: + 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( - section.ListSectionsResponse( - next_page_token="next_page_token_value", + space_notification_setting.SpaceNotificationSetting( + name="name_value", + notification_setting=space_notification_setting.SpaceNotificationSetting.NotificationSetting.ALL, + mute_setting=space_notification_setting.SpaceNotificationSetting.MuteSetting.UNMUTED, ) ) - response = await client.list_sections(request) + response = await client.get_space_notification_setting(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request = section.ListSectionsRequest() + request = space_notification_setting.GetSpaceNotificationSettingRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListSectionsAsyncPager) - assert response.next_page_token == "next_page_token_value" + 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 + ) -def test_list_sections_field_headers(): +def test_get_space_notification_setting_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.ListSectionsRequest() + request = space_notification_setting.GetSpaceNotificationSettingRequest() - request.parent = "parent_value" + request.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_sections), "__call__") as call: - call.return_value = section.ListSectionsResponse() - client.list_sections(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) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 @@ -15380,28 +15113,30 @@ def test_list_sections_field_headers(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "parent=parent_value", + "name=name_value", ) in kw["metadata"] @pytest.mark.asyncio -async def test_list_sections_field_headers_async(): +async def test_get_space_notification_setting_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.ListSectionsRequest() + request = space_notification_setting.GetSpaceNotificationSettingRequest() - request.parent = "parent_value" + request.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_sections), "__call__") as call: + with mock.patch.object( + type(client.transport.get_space_notification_setting), "__call__" + ) as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - section.ListSectionsResponse() + space_notification_setting.SpaceNotificationSetting() ) - await client.list_sections(request) + await client.get_space_notification_setting(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) @@ -15412,35 +15147,37 @@ async def test_list_sections_field_headers_async(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "parent=parent_value", + "name=name_value", ) in kw["metadata"] -def test_list_sections_flattened(): +def test_get_space_notification_setting_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: + 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 = section.ListSectionsResponse() + call.return_value = space_notification_setting.SpaceNotificationSetting() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - client.list_sections( - parent="parent_value", + client.get_space_notification_setting( + name="name_value", ) # Establish that the underlying call was made with the expected # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - arg = args[0].parent - mock_val = "parent_value" + arg = args[0].name + mock_val = "name_value" assert arg == mock_val -def test_list_sections_flattened_error(): +def test_get_space_notification_setting_flattened_error(): client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -15448,43 +15185,45 @@ def test_list_sections_flattened_error(): # 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", + client.get_space_notification_setting( + space_notification_setting.GetSpaceNotificationSettingRequest(), + name="name_value", ) @pytest.mark.asyncio -async def test_list_sections_flattened_async(): +async def test_get_space_notification_setting_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.list_sections), "__call__") as call: + 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 = section.ListSectionsResponse() + call.return_value = space_notification_setting.SpaceNotificationSetting() call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - section.ListSectionsResponse() + space_notification_setting.SpaceNotificationSetting() ) # 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", + response = await client.get_space_notification_setting( + name="name_value", ) # Establish that the underlying call was made with the expected # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - arg = args[0].parent - mock_val = "parent_value" + arg = args[0].name + mock_val = "name_value" assert arg == mock_val @pytest.mark.asyncio -async def test_list_sections_flattened_error_async(): +async def test_get_space_notification_setting_flattened_error_async(): client = ChatServiceAsyncClient( credentials=async_anonymous_credentials(), ) @@ -15492,210 +15231,20 @@ async def test_list_sections_flattened_error_async(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - await client.list_sections( - section.ListSectionsRequest(), - parent="parent_value", - ) - - -def test_list_sections_pager(transport_name: str = "grpc"): - client = ChatServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport_name, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_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, - ) - - 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) - - 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.Section) for i in results) - - -def test_list_sections_pages(transport_name: str = "grpc"): - client = ChatServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport_name, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_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 - - -@pytest.mark.asyncio -async def test_list_sections_async_pager(): - 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.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) - - assert len(responses) == 6 - assert all(isinstance(i, section.Section) for i in responses) - - -@pytest.mark.asyncio -async def test_list_sections_async_pages(): - 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.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, + await client.get_space_notification_setting( + space_notification_setting.GetSpaceNotificationSettingRequest(), + name="name_value", ) - pages = [] - async for page_ in (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 @pytest.mark.parametrize( "request_type", [ - section.PositionSectionRequest(), + gc_space_notification_setting.UpdateSpaceNotificationSettingRequest(), {}, ], ) -def test_position_section(request_type, transport: str = "grpc"): +def test_update_space_notification_setting(request_type, transport: str = "grpc"): client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -15706,22 +15255,37 @@ def test_position_section(request_type, transport: str = "grpc"): request = request_type # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.position_section), "__call__") as call: + 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 = section.PositionSectionResponse() - response = client.position_section(request) + call.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, + ) + response = client.update_space_notification_setting(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - request = section.PositionSectionRequest() + request = gc_space_notification_setting.UpdateSpaceNotificationSettingRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, section.PositionSectionResponse) + 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 + ) -def test_position_section_non_empty_request_with_auto_populated_field(): +def test_update_space_notification_setting_non_empty_request_with_auto_populated_field(): # 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( @@ -15732,25 +15296,25 @@ def test_position_section_non_empty_request_with_auto_populated_field(): # Populate all string fields in the request which are not UUID4 # since we want to check that UUID4 are populated automatically # if they meet the requirements of AIP 4235. - request = section.PositionSectionRequest( - name="name_value", - ) + request = gc_space_notification_setting.UpdateSpaceNotificationSettingRequest() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.position_section), "__call__") as call: + with mock.patch.object( + type(client.transport.update_space_notification_setting), "__call__" + ) as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.position_section(request=request) + client.update_space_notification_setting(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - request_msg = section.PositionSectionRequest( - name="name_value", + request_msg = ( + gc_space_notification_setting.UpdateSpaceNotificationSettingRequest() ) assert args[0] == request_msg -def test_position_section_use_cached_wrapped_rpc(): +def test_update_space_notification_setting_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -15764,23 +15328,26 @@ def test_position_section_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.position_section in client._transport._wrapped_methods + assert ( + client._transport.update_space_notification_setting + in client._transport._wrapped_methods + ) # Replace cached wrapped function with mock mock_rpc = 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 - ) + client._transport._wrapped_methods[ + client._transport.update_space_notification_setting + ] = mock_rpc request = {} - client.position_section(request) + client.update_space_notification_setting(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.position_section(request) + client.update_space_notification_setting(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -15788,7 +15355,7 @@ def test_position_section_use_cached_wrapped_rpc(): @pytest.mark.asyncio -async def test_position_section_async_use_cached_wrapped_rpc( +async def test_update_space_notification_setting_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", ): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, @@ -15805,7 +15372,7 @@ async def test_position_section_async_use_cached_wrapped_rpc( # Ensure method has been cached assert ( - client._client._transport.position_section + client._client._transport.update_space_notification_setting in client._client._transport._wrapped_methods ) @@ -15813,16 +15380,16 @@ async def test_position_section_async_use_cached_wrapped_rpc( mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() client._client._transport._wrapped_methods[ - client._client._transport.position_section + client._client._transport.update_space_notification_setting ] = mock_rpc request = {} - await client.position_section(request) + await client.update_space_notification_setting(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - await client.position_section(request) + await client.update_space_notification_setting(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -15833,11 +15400,13 @@ async def test_position_section_async_use_cached_wrapped_rpc( @pytest.mark.parametrize( "request_type", [ - section.PositionSectionRequest(), + gc_space_notification_setting.UpdateSpaceNotificationSettingRequest(), {}, ], ) -async def test_position_section_async(request_type, transport: str = "grpc_asyncio"): +async def test_update_space_notification_setting_async( + request_type, transport: str = "grpc_asyncio" +): client = ChatServiceAsyncClient( credentials=async_anonymous_credentials(), transport=transport, @@ -15848,38 +15417,55 @@ async def test_position_section_async(request_type, transport: str = "grpc_async request = request_type # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.position_section), "__call__") as call: + 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( - section.PositionSectionResponse() + 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, + ) ) - response = await client.position_section(request) + response = await client.update_space_notification_setting(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request = section.PositionSectionRequest() + request = gc_space_notification_setting.UpdateSpaceNotificationSettingRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, section.PositionSectionResponse) + 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 + ) -def test_position_section_field_headers(): +def test_update_space_notification_setting_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.PositionSectionRequest() + request = gc_space_notification_setting.UpdateSpaceNotificationSettingRequest() - request.name = "name_value" + request.space_notification_setting.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 = section.PositionSectionResponse() - client.position_section(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) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 @@ -15890,28 +15476,30 @@ def test_position_section_field_headers(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "name=name_value", + "space_notification_setting.name=name_value", ) in kw["metadata"] @pytest.mark.asyncio -async def test_position_section_field_headers_async(): +async def test_update_space_notification_setting_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.PositionSectionRequest() + request = gc_space_notification_setting.UpdateSpaceNotificationSettingRequest() - request.name = "name_value" + request.space_notification_setting.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: + with mock.patch.object( + type(client.transport.update_space_notification_setting), "__call__" + ) as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - section.PositionSectionResponse() + gc_space_notification_setting.SpaceNotificationSetting() ) - await client.position_section(request) + await client.update_space_notification_setting(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) @@ -15922,88 +15510,194 @@ async def test_position_section_field_headers_async(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "name=name_value", + "space_notification_setting.name=name_value", ) in kw["metadata"] -@pytest.mark.parametrize( - "request_type", - [ - section.ListSectionItemsRequest(), - {}, - ], -) -def test_list_section_items(request_type, transport: str = "grpc"): +def test_update_space_notification_setting_flattened(): 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.list_section_items), "__call__" + type(client.transport.update_space_notification_setting), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = section.ListSectionItemsResponse( - next_page_token="next_page_token_value", + call.return_value = gc_space_notification_setting.SpaceNotificationSetting() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_space_notification_setting( + space_notification_setting=gc_space_notification_setting.SpaceNotificationSetting( + name="name_value" + ), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) - response = client.list_section_items(request) - # Establish that the underlying gRPC stub method was called. + # Establish that the underlying call was made with the expected + # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - request = section.ListSectionItemsRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListSectionItemsPager) - assert response.next_page_token == "next_page_token_value" + arg = args[0].space_notification_setting + mock_val = gc_space_notification_setting.SpaceNotificationSetting( + 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_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. +def test_update_space_notification_setting_flattened_error(): 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.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.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"]), + ) + + +@pytest.mark.asyncio +async def test_update_space_notification_setting_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.list_section_items), "__call__" + type(client.transport.update_space_notification_setting), "__call__" ) as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. + # Designate an appropriate return value for the call. + call.return_value = gc_space_notification_setting.SpaceNotificationSetting() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gc_space_notification_setting.SpaceNotificationSetting() ) - client.list_section_items(request=request) - call.assert_called() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_space_notification_setting( + space_notification_setting=gc_space_notification_setting.SpaceNotificationSetting( + name="name_value" + ), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request_msg = section.ListSectionItemsRequest( - parent="parent_value", - page_token="page_token_value", - filter="filter_value", + arg = args[0].space_notification_setting + mock_val = gc_space_notification_setting.SpaceNotificationSetting( + name="name_value" ) - assert args[0] == request_msg + 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_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( +@pytest.mark.asyncio +async def test_update_space_notification_setting_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.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"]), + ) + + +@pytest.mark.parametrize( + "request_type", + [ + gc_section.CreateSectionRequest(), + {}, + ], +) +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] + request_msg = gc_section.CreateSectionRequest( + parent="parent_value", + ) + assert args[0] == request_msg + + +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="grpc", ) @@ -16013,25 +15707,21 @@ def test_list_section_items_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert ( - client._transport.list_section_items 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.list_section_items] = ( - mock_rpc - ) + client._transport._wrapped_methods[client._transport.create_section] = mock_rpc request = {} - client.list_section_items(request) + client.create_section(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.list_section_items(request) + client.create_section(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -16039,7 +15729,7 @@ def test_list_section_items_use_cached_wrapped_rpc(): @pytest.mark.asyncio -async def test_list_section_items_async_use_cached_wrapped_rpc( +async def test_create_section_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", ): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, @@ -16056,7 +15746,7 @@ async def test_list_section_items_async_use_cached_wrapped_rpc( # Ensure method has been cached assert ( - client._client._transport.list_section_items + client._client._transport.create_section in client._client._transport._wrapped_methods ) @@ -16064,16 +15754,16 @@ async def test_list_section_items_async_use_cached_wrapped_rpc( mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() client._client._transport._wrapped_methods[ - client._client._transport.list_section_items + client._client._transport.create_section ] = mock_rpc request = {} - await client.list_section_items(request) + await client.create_section(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - await client.list_section_items(request) + await client.create_section(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -16084,11 +15774,11 @@ async def test_list_section_items_async_use_cached_wrapped_rpc( @pytest.mark.parametrize( "request_type", [ - section.ListSectionItemsRequest(), + gc_section.CreateSectionRequest(), {}, ], ) -async def test_list_section_items_async(request_type, transport: str = "grpc_asyncio"): +async def test_create_section_async(request_type, transport: str = "grpc_asyncio"): client = ChatServiceAsyncClient( credentials=async_anonymous_credentials(), transport=transport, @@ -16099,45 +15789,47 @@ async def test_list_section_items_async(request_type, transport: str = "grpc_asy request = request_type # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_section_items), "__call__" - ) as call: + 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( - section.ListSectionItemsResponse( - next_page_token="next_page_token_value", + gc_section.Section( + name="name_value", + display_name="display_name_value", + sort_order=1091, + type_=gc_section.Section.SectionType.CUSTOM_SECTION, ) ) - response = await client.list_section_items(request) + response = await client.create_section(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request = section.ListSectionItemsRequest() + request = gc_section.CreateSectionRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListSectionItemsAsyncPager) - assert response.next_page_token == "next_page_token_value" + 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_list_section_items_field_headers(): +def test_create_section_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.ListSectionItemsRequest() + 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.list_section_items), "__call__" - ) as call: - call.return_value = section.ListSectionItemsResponse() - client.list_section_items(request) + with mock.patch.object(type(client.transport.create_section), "__call__") as call: + call.return_value = gc_section.Section() + client.create_section(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 @@ -16153,25 +15845,21 @@ def test_list_section_items_field_headers(): @pytest.mark.asyncio -async def test_list_section_items_field_headers_async(): +async def test_create_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.ListSectionItemsRequest() + 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.list_section_items), "__call__" - ) as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - section.ListSectionItemsResponse() - ) - await client.list_section_items(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) @@ -16186,21 +15874,20 @@ async def test_list_section_items_field_headers_async(): ) in kw["metadata"] -def test_list_section_items_flattened(): +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.list_section_items), "__call__" - ) as call: + with mock.patch.object(type(client.transport.create_section), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = section.ListSectionItemsResponse() + 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.list_section_items( + client.create_section( parent="parent_value", + section=gc_section.Section(name="name_value"), ) # Establish that the underlying call was made with the expected @@ -16210,9 +15897,12 @@ def test_list_section_items_flattened(): 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_list_section_items_flattened_error(): +def test_create_section_flattened_error(): client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -16220,32 +15910,30 @@ def test_list_section_items_flattened_error(): # 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(), + client.create_section( + gc_section.CreateSectionRequest(), parent="parent_value", + section=gc_section.Section(name="name_value"), ) @pytest.mark.asyncio -async def test_list_section_items_flattened_async(): +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.list_section_items), "__call__" - ) as call: + with mock.patch.object(type(client.transport.create_section), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = section.ListSectionItemsResponse() + call.return_value = gc_section.Section() - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - section.ListSectionItemsResponse() - ) + 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.list_section_items( + 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 @@ -16255,10 +15943,13 @@ async def test_list_section_items_flattened_async(): 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_list_section_items_flattened_error_async(): +async def test_create_section_flattened_error_async(): client = ChatServiceAsyncClient( credentials=async_anonymous_credentials(), ) @@ -16266,218 +15957,21 @@ async def test_list_section_items_flattened_error_async(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - await client.list_section_items( - section.ListSectionItemsRequest(), + await client.create_section( + gc_section.CreateSectionRequest(), parent="parent_value", + section=gc_section.Section(name="name_value"), ) -def test_list_section_items_pager(transport_name: str = "grpc"): - client = ChatServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport_name, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_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, - ) - - 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=transport_name, - ) - - # 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 - - -@pytest.mark.asyncio -async def test_list_section_items_async_pager(): - 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.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) - - assert len(responses) == 6 - assert all(isinstance(i, section.SectionItem) for i in responses) - - -@pytest.mark.asyncio -async def test_list_section_items_async_pages(): - 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.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 = [] - async for page_ in (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(), + section.DeleteSectionRequest(), {}, ], ) -def test_move_section_item(request_type, transport: str = "grpc"): +def test_delete_section(request_type, transport: str = "grpc"): client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -16488,24 +15982,22 @@ def test_move_section_item(request_type, transport: str = "grpc"): request = request_type # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.move_section_item), "__call__" - ) as call: + with mock.patch.object(type(client.transport.delete_section), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = section.MoveSectionItemResponse() - response = client.move_section_item(request) + 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.MoveSectionItemRequest() + request = section.DeleteSectionRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, section.MoveSectionItemResponse) + assert response is None -def test_move_section_item_non_empty_request_with_auto_populated_field(): +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( @@ -16516,29 +16008,25 @@ def test_move_section_item_non_empty_request_with_auto_populated_field(): # Populate all string fields in the request which are not UUID4 # since we want to check that UUID4 are populated automatically # if they meet the requirements of AIP 4235. - request = section.MoveSectionItemRequest( + request = section.DeleteSectionRequest( 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: + 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.move_section_item(request=request) + client.delete_section(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - request_msg = section.MoveSectionItemRequest( + request_msg = section.DeleteSectionRequest( name="name_value", - target_section="target_section_value", ) assert args[0] == request_msg -def test_move_section_item_use_cached_wrapped_rpc(): +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: @@ -16552,23 +16040,21 @@ def test_move_section_item_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.move_section_item 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.move_section_item] = ( - mock_rpc - ) + client._transport._wrapped_methods[client._transport.delete_section] = mock_rpc request = {} - client.move_section_item(request) + client.delete_section(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.move_section_item(request) + client.delete_section(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -16576,7 +16062,7 @@ def test_move_section_item_use_cached_wrapped_rpc(): @pytest.mark.asyncio -async def test_move_section_item_async_use_cached_wrapped_rpc( +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, @@ -16593,7 +16079,7 @@ async def test_move_section_item_async_use_cached_wrapped_rpc( # Ensure method has been cached assert ( - client._client._transport.move_section_item + client._client._transport.delete_section in client._client._transport._wrapped_methods ) @@ -16601,16 +16087,16 @@ async def test_move_section_item_async_use_cached_wrapped_rpc( mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() client._client._transport._wrapped_methods[ - client._client._transport.move_section_item + client._client._transport.delete_section ] = mock_rpc request = {} - await client.move_section_item(request) + await client.delete_section(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - await client.move_section_item(request) + await client.delete_section(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -16621,11 +16107,11 @@ async def test_move_section_item_async_use_cached_wrapped_rpc( @pytest.mark.parametrize( "request_type", [ - section.MoveSectionItemRequest(), + section.DeleteSectionRequest(), {}, ], ) -async def test_move_section_item_async(request_type, transport: str = "grpc_asyncio"): +async def test_delete_section_async(request_type, transport: str = "grpc_asyncio"): client = ChatServiceAsyncClient( credentials=async_anonymous_credentials(), transport=transport, @@ -16636,42 +16122,36 @@ async def test_move_section_item_async(request_type, transport: str = "grpc_asyn 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: + 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( - section.MoveSectionItemResponse() - ) - response = await client.move_section_item(request) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_section(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request = section.MoveSectionItemRequest() + request = section.DeleteSectionRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, section.MoveSectionItemResponse) + assert response is None -def test_move_section_item_field_headers(): +def test_delete_section_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 = 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.move_section_item), "__call__" - ) as call: - call.return_value = section.MoveSectionItemResponse() - client.move_section_item(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 @@ -16687,25 +16167,21 @@ def test_move_section_item_field_headers(): @pytest.mark.asyncio -async def test_move_section_item_field_headers_async(): +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.MoveSectionItemRequest() + 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.move_section_item), "__call__" - ) as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - section.MoveSectionItemResponse() - ) - await client.move_section_item(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) @@ -16720,22 +16196,19 @@ async def test_move_section_item_field_headers_async(): ) in kw["metadata"] -def test_move_section_item_flattened(): +def test_delete_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.move_section_item), "__call__" - ) as call: + with mock.patch.object(type(client.transport.delete_section), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = section.MoveSectionItemResponse() + call.return_value = None # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - client.move_section_item( + client.delete_section( name="name_value", - target_section="target_section_value", ) # Establish that the underlying call was made with the expected @@ -16745,12 +16218,9 @@ def test_move_section_item_flattened(): 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(): +def test_delete_section_flattened_error(): client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -16758,34 +16228,28 @@ def test_move_section_item_flattened_error(): # 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(), + client.delete_section( + section.DeleteSectionRequest(), name="name_value", - target_section="target_section_value", ) @pytest.mark.asyncio -async def test_move_section_item_flattened_async(): +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.move_section_item), "__call__" - ) as call: + with mock.patch.object(type(client.transport.delete_section), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = section.MoveSectionItemResponse() + call.return_value = None - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - section.MoveSectionItemResponse() - ) + 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.move_section_item( + response = await client.delete_section( name="name_value", - target_section="target_section_value", ) # Establish that the underlying call was made with the expected @@ -16795,13 +16259,10 @@ async def test_move_section_item_flattened_async(): 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(): +async def test_delete_section_flattened_error_async(): client = ChatServiceAsyncClient( credentials=async_anonymous_credentials(), ) @@ -16809,20 +16270,86 @@ async def test_move_section_item_flattened_error_async(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - await client.move_section_item( - section.MoveSectionItemRequest(), + await client.delete_section( + section.DeleteSectionRequest(), name="name_value", - target_section="target_section_value", ) -def test_create_message_rest_use_cached_wrapped_rpc(): +@pytest.mark.parametrize( + "request_type", + [ + gc_section.UpdateSectionRequest(), + {}, + ], +) +def test_update_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.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, + ) + response = client.update_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.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 + + +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", + ) + + # Populate all string fields in the 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] + request_msg = gc_section.UpdateSectionRequest() + assert args[0] == request_msg + + +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 @@ -16830,206 +16357,337 @@ 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.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.create_message] = mock_rpc - + client._transport._wrapped_methods[client._transport.update_section] = mock_rpc request = {} - client.create_message(request) + client.update_section(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.create_message(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_create_message_rest_required_fields( - request_type=gc_message.CreateMessageRequest, +@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() - ).create_message._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() - ).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( - ( - "create_message_notification_options", - "message_id", - "message_reply_option", - "request_id", - "thread_key", - ) + 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 +@pytest.mark.parametrize( + "request_type", + [ + gc_section.UpdateSectionRequest(), + {}, + ], +) +async def test_update_section_async(request_type, transport: str = "grpc_asyncio"): + 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 + + +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 = 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 + # Any value 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 = gc_message.Message.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.create_message(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 sorted(expected_params) == sorted(actual_params) +@pytest.mark.asyncio +async def test_update_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 = gc_section.UpdateSectionRequest() -def test_create_message_rest_unset_required_fields(): - transport = transports.ChatServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials + 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.create_message._get_unset_required_fields({}) - assert set(unset_fields) == ( - set( - ( - "createMessageNotificationOptions", - "messageId", - "messageReplyOption", - "requestId", - "threadKey", - ) - ) - & set( - ( - "parent", - "message", - ) + # 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"]), ) - ) + + # 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_create_message_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 = gc_message.Message() + # 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", - message=gc_message.Message(name="name_value"), - message_id="message_id_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 = 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.update_section), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = gc_section.Section() - client.create_message(**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/*}/messages" % 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 + + +@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): + 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_create_message_rest_flattened_error(transport: str = "rest"): +@pytest.mark.parametrize( + "request_type", + [ + section.ListSectionsRequest(), + {}, + ], +) +def test_list_sections(request_type, transport: str = "grpc"): 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(), + # Everything is optional in proto3 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_sections), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = section.ListSectionsResponse( + next_page_token="next_page_token_value", + ) + response = client.list_sections(request) + + # 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 + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListSectionsPager) + assert response.next_page_token == "next_page_token_value" + + +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] + request_msg = section.ListSectionsRequest( parent="parent_value", - message=gc_message.Message(name="name_value"), - message_id="message_id_value", + page_token="page_token_value", ) + assert args[0] == request_msg -def test_list_messages_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 @@ -17037,519 +16695,759 @@ 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.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_messages] = mock_rpc - + client._transport._wrapped_methods[client._transport.list_sections] = mock_rpc request = {} - client.list_messages(request) + client.list_sections(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.list_messages(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_list_messages_rest_required_fields(request_type=message.ListMessagesRequest): - transport_class = transports.ChatServiceRestTransport +@pytest.mark.asyncio +async def test_list_sections_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.list_sections + 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.list_sections + ] = mock_rpc - # verify required fields with default values are now present + request = {} + await client.list_sections(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", - ) + await 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 + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "request_type", + [ + section.ListSectionsRequest(), + {}, + ], +) +async def test_list_sections_async(request_type, transport: str = "grpc_asyncio"): + 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.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) + + # 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 + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListSectionsAsyncPager) + assert response.next_page_token == "next_page_token_value" + +def test_list_sections_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 = 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 - response_value = Response() - response_value.status_code = 200 + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = section.ListSectionsRequest() - # Convert return value to protobuf type - return_value = message.ListMessagesResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) + request.parent = "parent_value" - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_sections), "__call__") as call: + call.return_value = section.ListSectionsResponse() + client.list_sections(request) - response = client.list_messages(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request - expected_params = [("$alt", "json;enum-encoding=int")] - actual_params = req.call_args.kwargs["params"] - assert sorted(expected_params) == sorted(actual_params) + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] -def test_list_messages_rest_unset_required_fields(): - transport = transports.ChatServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials +@pytest.mark.asyncio +async def test_list_sections_field_headers_async(): + client = ChatServiceAsyncClient( + credentials=async_anonymous_credentials(), ) - unset_fields = transport.list_messages._get_unset_required_fields({}) - assert set(unset_fields) == ( - set( - ( - "filter", - "orderBy", - "pageSize", - "pageToken", - "showDeleted", - ) + # Any value 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" + + # 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() ) - & set(("parent",)) - ) + 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_list_messages_rest_flattened(): + # 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(), - transport="rest", ) - # Mock the http request call within the method and 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.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", + ) - # 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].parent + mock_val = "parent_value" + assert arg == mock_val - # get truthy value for each flattened field - mock_args = dict( + +def test_list_sections_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.list_sections( + section.ListSectionsRequest(), 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 = 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_list_sections_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.list_sections), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = section.ListSectionsResponse() + + 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", + ) # Establish that the underlying call was 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].parent + mock_val = "parent_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_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): - client.list_messages( - message.ListMessagesRequest(), + await client.list_sections( + section.ListSectionsRequest(), parent="parent_value", ) -def test_list_messages_rest_pager(transport: str = "rest"): +def test_list_sections_pager(transport_name: str = "grpc"): client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport=transport, + transport=transport_name, ) - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, "request") as req: - # TODO(kbandes): remove this mock unless there's a good reason for it. - # with mock.patch.object(path_template, 'transcode') as transcode: - # Set the response as a series of pages - response = ( - message.ListMessagesResponse( - messages=[ - message.Message(), - message.Message(), - message.Message(), + # 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", ), - message.ListMessagesResponse( - messages=[], + section.ListSectionsResponse( + sections=[], next_page_token="def", ), - message.ListMessagesResponse( - messages=[ - message.Message(), + section.ListSectionsResponse( + sections=[ + section.Section(), ], next_page_token="ghi", ), - message.ListMessagesResponse( - messages=[ - message.Message(), - message.Message(), + section.ListSectionsResponse( + sections=[ + section.Section(), + section.Section(), ], ), + RuntimeError, ) - # Two responses for two calls - response = response + response - - # 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 - sample_request = {"parent": "spaces/sample1"} + 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) - pager = client.list_messages(request=sample_request) + assert pager._metadata == expected_metadata + assert pager._retry == retry + assert pager._timeout == timeout results = list(pager) assert len(results) == 6 - assert all(isinstance(i, message.Message) for i in results) + assert all(isinstance(i, section.Section) 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_sections_pages(transport_name: str = "grpc"): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) -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", + # 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 - # Should 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 +@pytest.mark.asyncio +async def test_list_sections_async_pager(): + client = ChatServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_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, ) - client._transport._wrapped_methods[client._transport.list_memberships] = ( - mock_rpc + 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) - request = {} - client.list_memberships(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 + assert len(responses) == 6 + assert all(isinstance(i, section.Section) for i in responses) - 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 +@pytest.mark.asyncio +async def test_list_sections_async_pages(): + 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.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 = [] + async for page_ in (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_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( - json_format.MessageToJson(pb_request, use_integers_for_enums=False) +@pytest.mark.parametrize( + "request_type", + [ + section.PositionSectionRequest(), + {}, + ], +) +def test_position_section(request_type, transport: str = "grpc"): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, ) - # verify fields with default values are dropped - - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).list_memberships._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type - # verify required fields with default values are now present + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.position_section), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = section.PositionSectionResponse() + response = client.position_section(request) - jsonified_request["parent"] = "parent_value" + # 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 - 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", - ) - ) - jsonified_request.update(unset_fields) + # Establish that the response is the type that we expect. + assert isinstance(response, section.PositionSectionResponse) - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == "parent_value" +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="rest", + transport="grpc", ) - 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 + # Populate all string fields in the 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", + ) - 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.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] + request_msg = section.PositionSectionRequest( + name="name_value", + ) + assert args[0] == request_msg - # 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"} +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="grpc", + ) - response = client.list_memberships(request) + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() - expected_params = [("$alt", "json;enum-encoding=int")] - actual_params = req.call_args.kwargs["params"] - assert sorted(expected_params) == sorted(actual_params) + # 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 -def test_list_memberships_rest_unset_required_fields(): - transport = transports.ChatServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials - ) + client.position_section(request) - unset_fields = transport.list_memberships._get_unset_required_fields({}) - assert set(unset_fields) == ( - set( - ( - "filter", - "pageSize", - "pageToken", - "showGroups", - "showInvited", - "useAdminAccess", - ) + # 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_position_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, ) - & set(("parent",)) - ) + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() -def test_list_memberships_rest_flattened(): - client = ChatServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) + # Ensure method has been cached + assert ( + client._client._transport.position_section + in client._client._transport._wrapped_methods + ) - # Mock the http request call within the method and 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() + # 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 - # get arguments that satisfy an http rule for this method - sample_request = {"parent": "spaces/sample1"} + request = {} + await client.position_section(request) - # get truthy value for each flattened field - mock_args = dict( - parent="parent_value", - ) - mock_args.update(sample_request) + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 - # 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"} + await client.position_section(request) - client.list_memberships(**mock_args) + # 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(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate( - "%s/v1/{parent=spaces/*}/members" % client.transport._host, args[1] + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "request_type", + [ + section.PositionSectionRequest(), + {}, + ], +) +async def test_position_section_async(request_type, transport: str = "grpc_asyncio"): + 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.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) + + # 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_list_memberships_rest_flattened_error(transport: str = "rest"): + +def test_position_section_field_headers(): 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_memberships( - membership.ListMembershipsRequest(), - parent="parent_value", + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = section.PositionSectionRequest() + + request.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 = section.PositionSectionResponse() + client.position_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_position_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.PositionSectionRequest() + + request.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 = grpc_helpers_async.FakeUnaryUnaryCall( + section.PositionSectionResponse() ) + await client.position_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 -def test_list_memberships_rest_pager(transport: str = "rest"): + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] + + +@pytest.mark.parametrize( + "request_type", + [ + section.ListSectionItemsRequest(), + {}, + ], +) +def test_list_section_items(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_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", ) - 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_section_items(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.ListSectionItemsRequest() + 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.ListSectionItemsPager) + 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_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="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.ListSectionItemsRequest( + parent="parent_value", + page_token="page_token_value", + filter="filter_value", + ) -def test_get_membership_rest_use_cached_wrapped_rpc(): + # 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] + request_msg = section.ListSectionItemsRequest( + parent="parent_value", + page_token="page_token_value", + filter="filter_value", + ) + assert args[0] == request_msg + + +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 @@ -17557,545 +17455,538 @@ 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_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_membership] = mock_rpc - + client._transport._wrapped_methods[client._transport.list_section_items] = ( + mock_rpc + ) request = {} - client.get_membership(request) + client.list_section_items(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.get_membership(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_membership_rest_required_fields( - request_type=membership.GetMembershipRequest, +@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_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_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_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_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", - ) - 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 - - 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"} - - response = client.get_membership(request) - - expected_params = [("$alt", "json;enum-encoding=int")] - actual_params = req.call_args.kwargs["params"] - assert sorted(expected_params) == sorted(actual_params) - - -def test_get_membership_rest_unset_required_fields(): - transport = transports.ChatServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials - ) - - unset_fields = transport.get_membership._get_unset_required_fields({}) - assert set(unset_fields) == (set(("useAdminAccess",)) & set(("name",))) - - -def test_get_membership_rest_flattened(): - client = ChatServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", +@pytest.mark.asyncio +@pytest.mark.parametrize( + "request_type", + [ + section.ListSectionItemsRequest(), + {}, + ], +) +async def test_list_section_items_async(request_type, transport: str = "grpc_asyncio"): + client = ChatServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, ) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), "request") as req: - # Designate an appropriate value for the returned response. - return_value = membership.Membership() - - # get arguments that satisfy an http rule for this method - sample_request = {"name": "spaces/sample1/members/sample2"} + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type - # get truthy value for each flattened field - mock_args = dict( - 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: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + section.ListSectionItemsResponse( + next_page_token="next_page_token_value", + ) ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # 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 = await client.list_section_items(request) - client.get_membership(**mock_args) + # 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 - # Establish that the underlying call was 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] - ) + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListSectionItemsAsyncPager) + assert response.next_page_token == "next_page_token_value" -def test_get_membership_rest_flattened_error(transport: str = "rest"): +def test_list_section_items_field_headers(): 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 + # Any value 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() - # Replace cached wrapped function with mock - mock_rpc = 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.parent = "parent_value" - request = {} - client.get_message(request) + # 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 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_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) - ) - - # 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) - - # verify required fields with default values are now present - - jsonified_request["name"] = "name_value" + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).get_message._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "parent=parent_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" - client = ChatServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", +@pytest.mark.asyncio +async def test_list_section_items_field_headers_async(): + client = ChatServiceAsyncClient( + credentials=async_anonymous_credentials(), ) - 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 - - # 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"} - - response = client.get_message(request) + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = section.ListSectionItemsRequest() - expected_params = [("$alt", "json;enum-encoding=int")] - actual_params = req.call_args.kwargs["params"] - assert sorted(expected_params) == sorted(actual_params) + request.parent = "parent_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() + ) + await client.list_section_items(request) -def test_get_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) + _, args, _ = call.mock_calls[0] + assert args[0] == request - unset_fields = transport.get_message._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name",))) + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] -def test_get_message_rest_flattened(): +def test_list_section_items_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.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 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", ) - mock_args.update(sample_request) - - # 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"} - - 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/{name=spaces/*/messages/*}" % 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_message_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_message( - message.GetMessageRequest(), - name="name_value", + client.list_section_items( + section.ListSectionItemsRequest(), + parent="parent_value", ) -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: - 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.update_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_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() + ) + # 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", ) - client._transport._wrapped_methods[client._transport.update_message] = mock_rpc - - request = {} - client.update_message(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - 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 + # 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_update_message_rest_required_fields( - request_type=gc_message.UpdateMessageRequest, -): - 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) +@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() - ).update_message._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_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", + # 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", ) - ) - jsonified_request.update(unset_fields) - # verify required fields with non-default values are left alone +def test_list_section_items_pager(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 = 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 - - 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) + # 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, + ) - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)), + ) + pager = client.list_section_items(request={}, retry=retry, timeout=timeout) - response = client.update_message(request) + assert pager._metadata == expected_metadata + assert pager._retry == retry + assert pager._timeout == timeout - expected_params = [("$alt", "json;enum-encoding=int")] - actual_params = req.call_args.kwargs["params"] - assert sorted(expected_params) == sorted(actual_params) + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, section.SectionItem) for i in results) -def test_update_message_rest_unset_required_fields(): - transport = transports.ChatServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials +def test_list_section_items_pages(transport_name: str = "grpc"): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, ) - unset_fields = transport.update_message._get_unset_required_fields({}) - assert set(unset_fields) == ( - set( - ( - "allowMissing", - "updateMask", - ) + # 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, ) - & set( - ( - "message", - "updateMask", - ) + 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 + + +@pytest.mark.asyncio +async def test_list_section_items_async_pager(): + 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.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) + + assert len(responses) == 6 + assert all(isinstance(i, section.SectionItem) for i in responses) + + +@pytest.mark.asyncio +async def test_list_section_items_async_pages(): + 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.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 = [] + async for page_ in (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 + -def test_update_message_rest_flattened(): +@pytest.mark.parametrize( + "request_type", + [ + section.MoveSectionItemRequest(), + {}, + ], +) +def test_move_section_item(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 = gc_message.Message() - - # get arguments that satisfy an http rule for this method - sample_request = {"message": {"name": "spaces/sample1/messages/sample2"}} - - # 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) + # Everything is optional in proto3 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 = 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.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) - 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] + request = section.MoveSectionItemRequest() + 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 response is the type that we expect. + assert isinstance(response, section.MoveSectionItemResponse) -def test_update_message_rest_flattened_error(transport: str = "rest"): +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=transport, + transport="grpc", ) - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.update_message( - gc_message.UpdateMessageRequest(), - message=gc_message.Message(name="name_value"), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = 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] + request_msg = section.MoveSectionItemRequest( + name="name_value", + target_section="target_section_value", ) + assert args[0] == request_msg -def test_delete_message_rest_use_cached_wrapped_rpc(): +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 @@ -18103,206 +17994,313 @@ def test_delete_message_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.delete_message 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.delete_message] = mock_rpc - + client._transport._wrapped_methods[client._transport.move_section_item] = ( + mock_rpc + ) request = {} - client.delete_message(request) + client.move_section_item(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.delete_message(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_delete_message_rest_required_fields(request_type=message.DeleteMessageRequest): - transport_class = transports.ChatServiceRestTransport +@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, + ) - 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.move_section_item + in client._client._transport._wrapped_methods + ) - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).delete_message._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.move_section_item + ] = mock_rpc - # verify required fields with default values are now present + request = {} + await client.move_section_item(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() - ).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) + await client.move_section_item(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 + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "request_type", + [ + section.MoveSectionItemRequest(), + {}, + ], +) +async def test_move_section_item_async(request_type, transport: str = "grpc_asyncio"): + 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) + +def test_move_section_item_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 = 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 + # Any value 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() - response_value = Response() - response_value.status_code = 200 - json_return_value = "" + request.name = "name_value" - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.move_section_item), "__call__" + ) as call: + call.return_value = section.MoveSectionItemResponse() + client.move_section_item(request) - response = client.delete_message(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request - expected_params = [("$alt", "json;enum-encoding=int")] - actual_params = req.call_args.kwargs["params"] - assert sorted(expected_params) == sorted(actual_params) + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] -def test_delete_message_rest_unset_required_fields(): - transport = transports.ChatServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials +@pytest.mark.asyncio +async def test_move_section_item_field_headers_async(): + client = ChatServiceAsyncClient( + credentials=async_anonymous_credentials(), ) - unset_fields = transport.delete_message._get_unset_required_fields({}) - assert set(unset_fields) == (set(("force",)) & 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.MoveSectionItemRequest() + request.name = "name_value" -def test_delete_message_rest_flattened(): + # 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(), - transport="rest", ) - # Mock the http request call within the method and 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( + # 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", ) - 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] - ) + 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_delete_message_rest_flattened_error(transport: str = "rest"): +def test_move_section_item_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.delete_message( - message.DeleteMessageRequest(), + client.move_section_item( + section.MoveSectionItemRequest(), name="name_value", + target_section="target_section_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: - 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_move_section_item_flattened_async(): + client = ChatServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) - # Ensure method has been cached - assert client._transport.get_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.move_section_item), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = section.MoveSectionItemResponse() - # Replace cached 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.MoveSectionItemResponse() ) - client._transport._wrapped_methods[client._transport.get_attachment] = mock_rpc + # 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: + 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.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.create_message] = mock_rpc request = {} - client.get_attachment(request) + client.create_message(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.get_attachment(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_get_attachment_rest_required_fields( - request_type=attachment.GetAttachmentRequest, +def test_create_message_rest_required_fields( + request_type=gc_message.CreateMessageRequest, ): 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( @@ -18313,21 +18311,31 @@ def test_get_attachment_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).get_attachment._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 - jsonified_request["name"] = "name_value" + jsonified_request["parent"] = "parent_value" unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).get_attachment._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( + ( + "create_message_notification_options", + "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 "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(), @@ -18336,7 +18344,7 @@ def test_get_attachment_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = attachment.Attachment() + 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 @@ -18348,39 +18356,56 @@ def test_get_attachment_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 = attachment.Attachment.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.get_attachment(request) + response = client.create_message(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert sorted(expected_params) == sorted(actual_params) -def test_get_attachment_rest_unset_required_fields(): +def test_create_message_rest_unset_required_fields(): transport = transports.ChatServiceRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.get_attachment._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name",))) + unset_fields = transport.create_message._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "createMessageNotificationOptions", + "messageId", + "messageReplyOption", + "requestId", + "threadKey", + ) + ) + & set( + ( + "parent", + "message", + ) + ) + ) -def test_get_attachment_rest_flattened(): +def test_create_message_rest_flattened(): client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -18389,14 +18414,16 @@ def test_get_attachment_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 = attachment.Attachment() + return_value = gc_message.Message() # get arguments that satisfy an http rule for this method - sample_request = {"name": "spaces/sample1/messages/sample2/attachments/sample3"} + sample_request = {"parent": "spaces/sample1"} # get truthy value for each flattened field mock_args = dict( - name="name_value", + parent="parent_value", + message=gc_message.Message(name="name_value"), + message_id="message_id_value", ) mock_args.update(sample_request) @@ -18404,25 +18431,24 @@ def test_get_attachment_rest_flattened(): response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = attachment.Attachment.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"} - client.get_attachment(**mock_args) + client.create_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/*/attachments/*}" % client.transport._host, - args[1], + "%s/v1/{parent=spaces/*}/messages" % client.transport._host, args[1] ) -def test_get_attachment_rest_flattened_error(transport: str = "rest"): +def test_create_message_rest_flattened_error(transport: str = "rest"): client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -18431,13 +18457,15 @@ def test_get_attachment_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_attachment( - attachment.GetAttachmentRequest(), - name="name_value", + client.create_message( + gc_message.CreateMessageRequest(), + parent="parent_value", + message=gc_message.Message(name="name_value"), + message_id="message_id_value", ) -def test_upload_attachment_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: @@ -18451,38 +18479,33 @@ def test_upload_attachment_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.upload_attachment 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.upload_attachment] = ( - mock_rpc - ) + client._transport._wrapped_methods[client._transport.list_messages] = mock_rpc request = {} - client.upload_attachment(request) + client.list_messages(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.upload_attachment(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_upload_attachment_rest_required_fields( - request_type=attachment.UploadAttachmentRequest, -): +def test_list_messages_rest_required_fields(request_type=message.ListMessagesRequest): 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( @@ -18493,24 +18516,31 @@ def test_upload_attachment_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).upload_attachment._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["parent"] = "parent_value" - jsonified_request["filename"] = "filename_value" unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).upload_attachment._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( + ( + "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 "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(), @@ -18519,7 +18549,7 @@ def test_upload_attachment_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = attachment.UploadAttachmentResponse() + 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 @@ -18531,84 +18561,106 @@ def test_upload_attachment_rest_required_fields( pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "post", + "method": "get", "query_params": pb_request, } - transcode_result["body"] = pb_request transcode.return_value = transcode_result response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = attachment.UploadAttachmentResponse.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.upload_attachment(request) + response = client.list_messages(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert sorted(expected_params) == sorted(actual_params) -def test_upload_attachment_rest_unset_required_fields(): +def test_list_messages_rest_unset_required_fields(): transport = transports.ChatServiceRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.upload_attachment._get_unset_required_fields({}) + unset_fields = transport.list_messages._get_unset_required_fields({}) assert set(unset_fields) == ( - set(()) - & set( + set( ( - "parent", - "filename", + "filter", + "orderBy", + "pageSize", + "pageToken", + "showDeleted", ) ) + & set(("parent",)) ) -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", - ) +def test_list_messages_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 = message.ListMessagesResponse() - # Ensure method has been cached - assert client._transport.list_spaces in client._transport._wrapped_methods + # get arguments that satisfy an http rule for this method + sample_request = {"parent": "spaces/sample1"} - # Replace cached 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( + parent="parent_value", ) - client._transport._wrapped_methods[client._transport.list_spaces] = mock_rpc + mock_args.update(sample_request) - request = {} - client.list_spaces(request) + # 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"} - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 + client.list_messages(**mock_args) - client.list_spaces(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] + ) - # Establish 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_flattened_error(transport: str = "rest"): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) -def test_list_spaces_rest_pager(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_messages( + message.ListMessagesRequest(), + parent="parent_value", + ) + + +def test_list_messages_rest_pager(transport: str = "rest"): client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -18620,28 +18672,28 @@ def test_list_spaces_rest_pager(transport: str = "rest"): # 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(), + message.ListMessagesResponse( + messages=[ + message.Message(), + message.Message(), + message.Message(), ], next_page_token="abc", ), - space.ListSpacesResponse( - spaces=[], + message.ListMessagesResponse( + messages=[], next_page_token="def", ), - space.ListSpacesResponse( - spaces=[ - space.Space(), + message.ListMessagesResponse( + messages=[ + message.Message(), ], next_page_token="ghi", ), - space.ListSpacesResponse( - spaces=[ - space.Space(), - space.Space(), + message.ListMessagesResponse( + messages=[ + message.Message(), + message.Message(), ], ), ) @@ -18649,27 +18701,27 @@ def test_list_spaces_rest_pager(transport: str = "rest"): response = response + response # Wrap the values into proper Response objs - response = tuple(space.ListSpacesResponse.to_json(x) for x in response) + 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 - sample_request = {} + sample_request = {"parent": "spaces/sample1"} - pager = client.list_spaces(request=sample_request) + pager = client.list_messages(request=sample_request) results = list(pager) assert len(results) == 6 - assert all(isinstance(i, space.Space) for i in results) + assert all(isinstance(i, message.Message) for i in results) - pages = list(client.list_spaces(request=sample_request).pages) + 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_search_spaces_rest_use_cached_wrapped_rpc(): +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: @@ -18683,33 +18735,37 @@ 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.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.search_spaces] = mock_rpc + client._transport._wrapped_methods[client._transport.list_memberships] = ( + mock_rpc + ) request = {} - client.search_spaces(request) + client.list_memberships(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.search_spaces(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_search_spaces_rest_required_fields(request_type=space.SearchSpacesRequest): +def test_list_memberships_rest_required_fields( + request_type=membership.ListMembershipsRequest, +): 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( @@ -18717,37 +18773,35 @@ 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) + ).list_memberships._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) + ).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( ( - "order_by", + "filter", "page_size", "page_token", - "query", + "show_groups", + "show_invited", "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" + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -18756,7 +18810,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 = 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 @@ -18777,47 +18831,98 @@ def test_search_spaces_rest_required_fields(request_type=space.SearchSpacesReque response_value.status_code = 200 # Convert return value to protobuf type - return_value = space.SearchSpacesResponse.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.search_spaces(request) + response = client.list_memberships(request) - expected_params = [ - ( - "query", - "", - ), - ("$alt", "json;enum-encoding=int"), - ] + expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert sorted(expected_params) == sorted(actual_params) -def test_search_spaces_rest_unset_required_fields(): +def test_list_memberships_rest_unset_required_fields(): transport = transports.ChatServiceRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.search_spaces._get_unset_required_fields({}) + unset_fields = transport.list_memberships._get_unset_required_fields({}) assert set(unset_fields) == ( set( ( - "orderBy", + "filter", "pageSize", "pageToken", - "query", + "showGroups", + "showInvited", "useAdminAccess", ) ) - & set(("query",)) + & set(("parent",)) ) -def test_search_spaces_rest_pager(transport: str = "rest"): +def test_list_memberships_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 = membership.ListMembershipsResponse() + + # 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) + + # 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"} + + 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/{parent=spaces/*}/members" % client.transport._host, args[1] + ) + + +def test_list_memberships_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_memberships( + membership.ListMembershipsRequest(), + parent="parent_value", + ) + + +def test_list_memberships_rest_pager(transport: str = "rest"): client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -18829,28 +18934,28 @@ def test_search_spaces_rest_pager(transport: str = "rest"): # 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(), + membership.ListMembershipsResponse( + memberships=[ + membership.Membership(), + membership.Membership(), + membership.Membership(), ], next_page_token="abc", ), - space.SearchSpacesResponse( - spaces=[], + membership.ListMembershipsResponse( + memberships=[], next_page_token="def", ), - space.SearchSpacesResponse( - spaces=[ - space.Space(), + membership.ListMembershipsResponse( + memberships=[ + membership.Membership(), ], next_page_token="ghi", ), - space.SearchSpacesResponse( - spaces=[ - space.Space(), - space.Space(), + membership.ListMembershipsResponse( + memberships=[ + membership.Membership(), + membership.Membership(), ], ), ) @@ -18858,27 +18963,29 @@ def test_search_spaces_rest_pager(transport: str = "rest"): response = response + response # Wrap the values into proper Response objs - response = tuple(space.SearchSpacesResponse.to_json(x) for x in response) + 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 = {} + sample_request = {"parent": "spaces/sample1"} - pager = client.search_spaces(request=sample_request) + pager = client.list_memberships(request=sample_request) results = list(pager) assert len(results) == 6 - assert all(isinstance(i, space.Space) for i in results) + assert all(isinstance(i, membership.Membership) for i in results) - pages = list(client.search_spaces(request=sample_request).pages) + 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_space_rest_use_cached_wrapped_rpc(): +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: @@ -18892,29 +18999,31 @@ 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.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.get_space] = mock_rpc + client._transport._wrapped_methods[client._transport.get_membership] = mock_rpc request = {} - client.get_space(request) + client.get_membership(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.get_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_get_space_rest_required_fields(request_type=space.GetSpaceRequest): +def test_get_membership_rest_required_fields( + request_type=membership.GetMembershipRequest, +): transport_class = transports.ChatServiceRestTransport request_init = {} @@ -18929,7 +19038,7 @@ 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) + ).get_membership._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present @@ -18938,7 +19047,7 @@ 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) + ).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) @@ -18954,7 +19063,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 = 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 @@ -18975,30 +19084,30 @@ 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 = 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(request) + response = client.get_membership(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert sorted(expected_params) == sorted(actual_params) -def test_get_space_rest_unset_required_fields(): +def test_get_membership_rest_unset_required_fields(): transport = transports.ChatServiceRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.get_space._get_unset_required_fields({}) + unset_fields = transport.get_membership._get_unset_required_fields({}) assert set(unset_fields) == (set(("useAdminAccess",)) & set(("name",))) -def test_get_space_rest_flattened(): +def test_get_membership_rest_flattened(): client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -19007,10 +19116,10 @@ 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 = membership.Membership() # get arguments that satisfy an http rule for this method - sample_request = {"name": "spaces/sample1"} + sample_request = {"name": "spaces/sample1/members/sample2"} # get truthy value for each flattened field mock_args = dict( @@ -19022,24 +19131,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 = 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(**mock_args) + 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/*}" % client.transport._host, args[1] + "%s/v1/{name=spaces/*/members/*}" % client.transport._host, args[1] ) -def test_get_space_rest_flattened_error(transport: str = "rest"): +def test_get_membership_rest_flattened_error(transport: str = "rest"): client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -19048,13 +19157,13 @@ 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(), + client.get_membership( + membership.GetMembershipRequest(), name="name_value", ) -def test_create_space_rest_use_cached_wrapped_rpc(): +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: @@ -19068,32 +19177,33 @@ def test_create_space_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.create_space in client._transport._wrapped_methods + 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.create_space] = mock_rpc + client._transport._wrapped_methods[client._transport.get_message] = mock_rpc request = {} - client.create_space(request) + client.get_message(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.create_space(request) + 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_create_space_rest_required_fields(request_type=gc_space.CreateSpaceRequest): +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( @@ -19104,19 +19214,21 @@ 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) + ).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() - ).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",)) + ).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(), @@ -19125,7 +19237,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 = 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 @@ -19137,40 +19249,39 @@ 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 = 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.create_space(request) + response = client.get_message(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert sorted(expected_params) == sorted(actual_params) -def test_create_space_rest_unset_required_fields(): +def test_get_message_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.get_message._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) -def test_create_space_rest_flattened(): +def test_get_message_rest_flattened(): client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -19179,14 +19290,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 = message.Message() # get arguments that satisfy an http rule for this method - sample_request = {} + sample_request = {"name": "spaces/sample1/messages/sample2"} # get truthy value for each flattened field mock_args = dict( - space=gc_space.Space(name="name_value"), + name="name_value", ) mock_args.update(sample_request) @@ -19194,22 +19305,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 = 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.create_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/spaces" % client.transport._host, args[1]) + assert path_template.validate( + "%s/v1/{name=spaces/*/messages/*}" % client.transport._host, args[1] + ) -def test_create_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, @@ -19218,13 +19331,13 @@ 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.get_message( + message.GetMessageRequest(), + name="name_value", ) -def test_set_up_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: @@ -19238,29 +19351,31 @@ 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.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.set_up_space] = mock_rpc + client._transport._wrapped_methods[client._transport.update_message] = mock_rpc request = {} - client.set_up_space(request) + client.update_message(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.set_up_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_set_up_space_rest_required_fields(request_type=space_setup.SetUpSpaceRequest): +def test_update_message_rest_required_fields( + request_type=gc_message.UpdateMessageRequest, +): transport_class = transports.ChatServiceRestTransport request_init = {} @@ -19274,14 +19389,21 @@ 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) + ).update_message._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() - ).set_up_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( + ( + "allow_missing", + "update_mask", + ) + ) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone @@ -19293,7 +19415,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 = 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 @@ -19305,7 +19427,7 @@ 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": "put", "query_params": pb_request, } transcode_result["body"] = pb_request @@ -19315,30 +19437,101 @@ def test_set_up_space_rest_required_fields(request_type=space_setup.SetUpSpaceRe response_value.status_code = 200 # Convert return value to protobuf type - return_value = space.Space.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.set_up_space(request) + response = client.update_message(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert sorted(expected_params) == sorted(actual_params) -def test_set_up_space_rest_unset_required_fields(): +def test_update_message_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.update_message._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "allowMissing", + "updateMask", + ) + ) + & set( + ( + "message", + "updateMask", + ) + ) + ) -def test_update_space_rest_use_cached_wrapped_rpc(): +def test_update_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 = gc_message.Message() + + # get arguments that satisfy an http rule for this method + sample_request = {"message": {"name": "spaces/sample1/messages/sample2"}} + + # 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) + + # 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"} + + 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/{message.name=spaces/*/messages/*}" % client.transport._host, args[1] + ) + + +def test_update_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.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: @@ -19352,32 +19545,33 @@ def test_update_space_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.update_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.update_space] = mock_rpc + client._transport._wrapped_methods[client._transport.delete_message] = mock_rpc request = {} - client.update_space(request) + client.delete_message(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.update_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_update_space_rest_required_fields(request_type=gc_space.UpdateSpaceRequest): +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( @@ -19388,24 +19582,23 @@ 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) + ).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" + unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).update_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( - ( - "update_mask", - "use_admin_access", - ) - ) + assert not set(unset_fields) - set(("force",)) 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(), @@ -19414,7 +19607,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 = 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 @@ -19426,53 +19619,36 @@ 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": "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.Space.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(request) + response = client.delete_message(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert sorted(expected_params) == sorted(actual_params) -def test_update_space_rest_unset_required_fields(): +def test_delete_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.delete_message._get_unset_required_fields({}) + assert set(unset_fields) == (set(("force",)) & set(("name",))) -def test_update_space_rest_flattened(): +def test_delete_message_rest_flattened(): client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -19481,40 +19657,37 @@ 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 = None # 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) # 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) + 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(**mock_args) + 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/{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_delete_message_rest_flattened_error(transport: str = "rest"): client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -19523,14 +19696,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.delete_message( + message.DeleteMessageRequest(), + name="name_value", ) -def test_delete_space_rest_use_cached_wrapped_rpc(): +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: @@ -19544,29 +19716,31 @@ 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.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.delete_space] = mock_rpc + client._transport._wrapped_methods[client._transport.get_attachment] = mock_rpc request = {} - client.delete_space(request) + client.get_attachment(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.delete_space(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_delete_space_rest_required_fields(request_type=space.DeleteSpaceRequest): +def test_get_attachment_rest_required_fields( + request_type=attachment.GetAttachmentRequest, +): transport_class = transports.ChatServiceRestTransport request_init = {} @@ -19581,7 +19755,7 @@ 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) + ).get_attachment._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present @@ -19590,9 +19764,7 @@ 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) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("use_admin_access",)) + ).get_attachment._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone @@ -19606,7 +19778,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 = 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 @@ -19618,36 +19790,39 @@ 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": "get", "query_params": 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 = 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.delete_space(request) + response = client.get_attachment(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert sorted(expected_params) == sorted(actual_params) -def test_delete_space_rest_unset_required_fields(): +def test_get_attachment_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.get_attachment._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) -def test_delete_space_rest_flattened(): +def test_get_attachment_rest_flattened(): client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -19656,10 +19831,10 @@ 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 = attachment.Attachment() # get arguments that satisfy an http rule for this method - sample_request = {"name": "spaces/sample1"} + sample_request = {"name": "spaces/sample1/messages/sample2/attachments/sample3"} # get truthy value for each flattened field mock_args = dict( @@ -19670,23 +19845,26 @@ def test_delete_space_rest_flattened(): # 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 = 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.delete_space(**mock_args) + 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/*}" % client.transport._host, args[1] + "%s/v1/{name=spaces/*/messages/*/attachments/*}" % client.transport._host, + args[1], ) -def test_delete_space_rest_flattened_error(transport: str = "rest"): +def test_get_attachment_rest_flattened_error(transport: str = "rest"): client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -19695,13 +19873,13 @@ 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(), + client.get_attachment( + attachment.GetAttachmentRequest(), name="name_value", ) -def test_complete_import_space_rest_use_cached_wrapped_rpc(): +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: @@ -19715,40 +19893,38 @@ 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.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.complete_import_space] = ( + client._transport._wrapped_methods[client._transport.upload_attachment] = ( mock_rpc ) request = {} - client.complete_import_space(request) + client.upload_attachment(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.complete_import_space(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_complete_import_space_rest_required_fields( - request_type=space.CompleteImportSpaceRequest, +def test_upload_attachment_rest_required_fields( + request_type=attachment.UploadAttachmentRequest, ): transport_class = transports.ChatServiceRestTransport request_init = {} - request_init["name"] = "" + request_init["parent"] = "" + request_init["filename"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -19759,21 +19935,24 @@ 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) + ).upload_attachment._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present - jsonified_request["name"] = "name_value" + jsonified_request["parent"] = "parent_value" + jsonified_request["filename"] = "filename_value" unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).complete_import_space._get_unset_required_fields(jsonified_request) + ).upload_attachment._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == "name_value" + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + assert "filename" in jsonified_request + assert jsonified_request["filename"] == "filename_value" client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -19782,7 +19961,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 = 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 @@ -19804,30 +19983,38 @@ def test_complete_import_space_rest_required_fields( response_value.status_code = 200 # Convert return value to protobuf type - return_value = space.CompleteImportSpaceResponse.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.complete_import_space(request) + response = client.upload_attachment(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert sorted(expected_params) == sorted(actual_params) -def test_complete_import_space_rest_unset_required_fields(): +def test_upload_attachment_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.upload_attachment._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(()) + & set( + ( + "parent", + "filename", + ) + ) + ) -def test_find_direct_message_rest_use_cached_wrapped_rpc(): +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: @@ -19841,39 +20028,130 @@ 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.list_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.find_direct_message] = ( - mock_rpc + client._transport._wrapped_methods[client._transport.list_spaces] = mock_rpc + + request = {} + client.list_spaces(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 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_list_spaces_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.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) + + 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: + 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.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.search_spaces] = mock_rpc request = {} - client.find_direct_message(request) + client.search_spaces(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.find_direct_message(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_find_direct_message_rest_required_fields( - request_type=space.FindDirectMessageRequest, -): +def test_search_spaces_rest_required_fields(request_type=space.SearchSpacesRequest): transport_class = transports.ChatServiceRestTransport request_init = {} - request_init["name"] = "" + request_init["query"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -19881,29 +20159,37 @@ def test_find_direct_message_rest_required_fields( ) # verify fields with default values are dropped - assert "name" not in jsonified_request + assert "query" not in jsonified_request unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).find_direct_message._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 "name" in jsonified_request - assert jsonified_request["name"] == request_init["name"] + assert "query" in jsonified_request + assert jsonified_request["query"] == request_init["query"] - jsonified_request["name"] = "name_value" + jsonified_request["query"] = "query_value" unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).find_direct_message._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(("name",)) + assert not set(unset_fields) - set( + ( + "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 "name" in jsonified_request - assert jsonified_request["name"] == "name_value" + assert "query" in jsonified_request + assert jsonified_request["query"] == "query_value" client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -19912,7 +20198,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 = 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 @@ -19933,18 +20219,18 @@ 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 = 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.find_direct_message(request) + response = client.search_spaces(request) expected_params = [ ( - "name", + "query", "", ), ("$alt", "json;enum-encoding=int"), @@ -19953,54 +20239,27 @@ def test_find_direct_message_rest_required_fields( assert sorted(expected_params) == sorted(actual_params) -def test_find_direct_message_rest_unset_required_fields(): +def test_search_spaces_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_find_group_chats_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached 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.find_group_chats in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_group_chats] = ( - mock_rpc + unset_fields = transport.search_spaces._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "orderBy", + "pageSize", + "pageToken", + "query", + "useAdminAccess", + ) ) - - request = {} - client.find_group_chats(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.find_group_chats(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 + & set(("query",)) + ) -def test_find_group_chats_rest_pager(transport: str = "rest"): +def test_search_spaces_rest_pager(transport: str = "rest"): client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -20012,7 +20271,7 @@ def test_find_group_chats_rest_pager(transport: str = "rest"): # with mock.patch.object(path_template, 'transcode') as transcode: # Set the response as a series of pages response = ( - space.FindGroupChatsResponse( + space.SearchSpacesResponse( spaces=[ space.Space(), space.Space(), @@ -20020,17 +20279,17 @@ def test_find_group_chats_rest_pager(transport: str = "rest"): ], next_page_token="abc", ), - space.FindGroupChatsResponse( + space.SearchSpacesResponse( spaces=[], next_page_token="def", ), - space.FindGroupChatsResponse( + space.SearchSpacesResponse( spaces=[ space.Space(), ], next_page_token="ghi", ), - space.FindGroupChatsResponse( + space.SearchSpacesResponse( spaces=[ space.Space(), space.Space(), @@ -20041,7 +20300,7 @@ def test_find_group_chats_rest_pager(transport: str = "rest"): response = response + response # Wrap the values into proper Response objs - response = tuple(space.FindGroupChatsResponse.to_json(x) for x in response) + 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") @@ -20050,18 +20309,18 @@ def test_find_group_chats_rest_pager(transport: str = "rest"): sample_request = {} - pager = client.find_group_chats(request=sample_request) + pager = client.search_spaces(request=sample_request) results = list(pager) assert len(results) == 6 assert all(isinstance(i, space.Space) for i in results) - pages = list(client.find_group_chats(request=sample_request).pages) + 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_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: @@ -20075,37 +20334,33 @@ 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.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.create_membership] = ( - mock_rpc - ) + client._transport._wrapped_methods[client._transport.get_space] = mock_rpc request = {} - client.create_membership(request) + client.get_space(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.create_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_create_membership_rest_required_fields( - request_type=gc_membership.CreateMembershipRequest, -): +def test_get_space_rest_required_fields(request_type=space.GetSpaceRequest): transport_class = transports.ChatServiceRestTransport request_init = {} - request_init["parent"] = "" + request_init["name"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -20116,23 +20371,23 @@ def test_create_membership_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).create_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 - jsonified_request["parent"] = "parent_value" + jsonified_request["name"] = "name_value" unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).create_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) # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == "parent_value" + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -20141,7 +20396,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 = 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 @@ -20153,48 +20408,39 @@ def test_create_membership_rest_required_fields( pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "post", + "method": "get", "query_params": pb_request, } - transcode_result["body"] = pb_request transcode.return_value = transcode_result response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = gc_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.create_membership(request) + response = client.get_space(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert sorted(expected_params) == sorted(actual_params) -def test_create_membership_rest_unset_required_fields(): +def test_get_space_rest_unset_required_fields(): transport = transports.ChatServiceRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.create_membership._get_unset_required_fields({}) - assert set(unset_fields) == ( - set(("useAdminAccess",)) - & set( - ( - "parent", - "membership", - ) - ) - ) + unset_fields = transport.get_space._get_unset_required_fields({}) + assert set(unset_fields) == (set(("useAdminAccess",)) & set(("name",))) -def test_create_membership_rest_flattened(): +def test_get_space_rest_flattened(): client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -20203,15 +20449,14 @@ def test_create_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 = gc_membership.Membership() + return_value = space.Space() # get arguments that satisfy an http rule for this method - sample_request = {"parent": "spaces/sample1"} + sample_request = {"name": "spaces/sample1"} # get truthy value for each flattened field mock_args = dict( - parent="parent_value", - membership=gc_membership.Membership(name="name_value"), + name="name_value", ) mock_args.update(sample_request) @@ -20219,24 +20464,24 @@ def test_create_membership_rest_flattened(): 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.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_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/{parent=spaces/*}/members" % client.transport._host, args[1] + "%s/v1/{name=spaces/*}" % client.transport._host, args[1] ) -def test_create_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, @@ -20245,14 +20490,13 @@ def test_create_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.create_membership( - gc_membership.CreateMembershipRequest(), - parent="parent_value", - membership=gc_membership.Membership(name="name_value"), + client.get_space( + space.GetSpaceRequest(), + name="name_value", ) -def test_update_membership_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: @@ -20266,33 +20510,29 @@ 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.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.update_membership] = ( - mock_rpc - ) + client._transport._wrapped_methods[client._transport.create_space] = mock_rpc request = {} - client.update_membership(request) + client.create_space(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.update_membership(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_update_membership_rest_required_fields( - request_type=gc_membership.UpdateMembershipRequest, -): +def test_create_space_rest_required_fields(request_type=gc_space.CreateSpaceRequest): transport_class = transports.ChatServiceRestTransport request_init = {} @@ -20306,21 +20546,16 @@ def test_update_membership_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).update_membership._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 unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).update_membership._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( - ( - "update_mask", - "use_admin_access", - ) - ) + assert not set(unset_fields) - set(("request_id",)) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone @@ -20332,7 +20567,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 = 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 @@ -20344,7 +20579,7 @@ def test_update_membership_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 @@ -20354,43 +20589,30 @@ def test_update_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 = 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_membership(request) + response = client.create_space(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert sorted(expected_params) == sorted(actual_params) -def test_update_membership_rest_unset_required_fields(): +def test_create_space_rest_unset_required_fields(): transport = transports.ChatServiceRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.update_membership._get_unset_required_fields({}) - assert set(unset_fields) == ( - set( - ( - "updateMask", - "useAdminAccess", - ) - ) - & set( - ( - "membership", - "updateMask", - ) - ) - ) + unset_fields = transport.create_space._get_unset_required_fields({}) + assert set(unset_fields) == (set(("requestId",)) & set(("space",))) -def test_update_membership_rest_flattened(): +def test_create_space_rest_flattened(): client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -20399,15 +20621,14 @@ def test_update_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 = gc_membership.Membership() + return_value = gc_space.Space() # get arguments that satisfy an http rule for this method - sample_request = {"membership": {"name": "spaces/sample1/members/sample2"}} + sample_request = {} # 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"]), + space=gc_space.Space(name="name_value"), ) mock_args.update(sample_request) @@ -20415,25 +20636,22 @@ def test_update_membership_rest_flattened(): response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = gc_membership.Membership.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.update_membership(**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/{membership.name=spaces/*/members/*}" % client.transport._host, - args[1], - ) + assert path_template.validate("%s/v1/spaces" % client.transport._host, args[1]) -def test_update_membership_rest_flattened_error(transport: str = "rest"): +def test_create_space_rest_flattened_error(transport: str = "rest"): client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -20442,14 +20660,13 @@ def test_update_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.update_membership( - gc_membership.UpdateMembershipRequest(), - membership=gc_membership.Membership(name="name_value"), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + client.create_space( + gc_space.CreateSpaceRequest(), + space=gc_space.Space(name="name_value"), ) -def test_delete_membership_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: @@ -20463,37 +20680,32 @@ 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.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.delete_membership] = ( - mock_rpc - ) + client._transport._wrapped_methods[client._transport.set_up_space] = mock_rpc request = {} - client.delete_membership(request) + client.set_up_space(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.delete_membership(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_delete_membership_rest_required_fields( - request_type=membership.DeleteMembershipRequest, -): +def test_set_up_space_rest_required_fields(request_type=space_setup.SetUpSpaceRequest): transport_class = transports.ChatServiceRestTransport request_init = {} - request_init["name"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -20504,23 +20716,17 @@ def test_delete_membership_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).delete_membership._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["name"] = "name_value" - unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).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",)) + ).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 "name" in jsonified_request - assert jsonified_request["name"] == "name_value" client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -20529,7 +20735,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 @@ -20541,95 +20747,40 @@ def test_delete_membership_rest_required_fields( pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "delete", + "method": "post", "query_params": pb_request, } + transcode_result["body"] = pb_request transcode.return_value = transcode_result response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = 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.set_up_space(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert sorted(expected_params) == sorted(actual_params) -def test_delete_membership_rest_unset_required_fields(): +def test_set_up_space_rest_unset_required_fields(): transport = transports.ChatServiceRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.delete_membership._get_unset_required_fields({}) - assert set(unset_fields) == (set(("useAdminAccess",)) & set(("name",))) - - -def test_delete_membership_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 = membership.Membership() - - # get arguments that satisfy an http rule for this method - sample_request = {"name": "spaces/sample1/members/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 - # 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.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=spaces/*/members/*}" % client.transport._host, args[1] - ) - - -def test_delete_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.delete_membership( - membership.DeleteMembershipRequest(), - name="name_value", - ) + unset_fields = transport.set_up_space._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("space",))) -def test_create_reaction_rest_use_cached_wrapped_rpc(): +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: @@ -20643,35 +20794,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.update_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.update_space] = mock_rpc request = {} - client.create_reaction(request) + client.update_space(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.create_reaction(request) + 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_create_reaction_rest_required_fields( - request_type=gc_reaction.CreateReactionRequest, -): +def test_update_space_rest_required_fields(request_type=gc_space.UpdateSpaceRequest): transport_class = transports.ChatServiceRestTransport request_init = {} - request_init["parent"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -20682,21 +20830,24 @@ def test_create_reaction_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).create_reaction._get_unset_required_fields(jsonified_request) + ).update_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) - jsonified_request.update(unset_fields) - + ).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 - assert "parent" in jsonified_request - assert jsonified_request["parent"] == "parent_value" client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -20705,7 +20856,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 @@ -20717,7 +20868,7 @@ def test_create_reaction_rest_required_fields( pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "post", + "method": "patch", "query_params": pb_request, } transcode_result["body"] = pb_request @@ -20727,38 +20878,43 @@ 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.update_space(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert sorted(expected_params) == sorted(actual_params) -def test_create_reaction_rest_unset_required_fields(): +def test_update_space_rest_unset_required_fields(): transport = transports.ChatServiceRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.create_reaction._get_unset_required_fields({}) + unset_fields = transport.update_space._get_unset_required_fields({}) assert set(unset_fields) == ( - set(()) + set( + ( + "updateMask", + "useAdminAccess", + ) + ) & set( ( - "parent", - "reaction", + "space", + "updateMask", ) ) ) -def test_create_reaction_rest_flattened(): +def test_update_space_rest_flattened(): client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -20767,15 +20923,15 @@ 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 = {"space": {"name": "spaces/sample1"}} # 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"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) mock_args.update(sample_request) @@ -20783,25 +20939,24 @@ 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.update_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], + "%s/v1/{space.name=spaces/*}" % client.transport._host, args[1] ) -def test_create_reaction_rest_flattened_error(transport: str = "rest"): +def test_update_space_rest_flattened_error(transport: str = "rest"): client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -20810,14 +20965,14 @@ 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.update_space( + gc_space.UpdateSpaceRequest(), + space=gc_space.Space(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) -def test_list_reactions_rest_use_cached_wrapped_rpc(): +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: @@ -20831,35 +20986,33 @@ 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.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.list_reactions] = mock_rpc + client._transport._wrapped_methods[client._transport.delete_space] = mock_rpc request = {} - client.list_reactions(request) + client.delete_space(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.list_reactions(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_list_reactions_rest_required_fields( - request_type=reaction.ListReactionsRequest, -): +def test_delete_space_rest_required_fields(request_type=space.DeleteSpaceRequest): transport_class = transports.ChatServiceRestTransport request_init = {} - request_init["parent"] = "" + request_init["name"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -20870,29 +21023,23 @@ def test_list_reactions_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).list_reactions._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 - jsonified_request["parent"] = "parent_value" + jsonified_request["name"] = "name_value" unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).list_reactions._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( - ( - "filter", - "page_size", - "page_token", - ) - ) + 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 "parent" in jsonified_request - assert jsonified_request["parent"] == "parent_value" + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -20901,7 +21048,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 = 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 @@ -20913,48 +21060,36 @@ def test_list_reactions_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 = 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_space(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert sorted(expected_params) == sorted(actual_params) -def test_list_reactions_rest_unset_required_fields(): +def test_delete_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.delete_space._get_unset_required_fields({}) + assert set(unset_fields) == (set(("useAdminAccess",)) & set(("name",))) -def test_list_reactions_rest_flattened(): +def test_delete_space_rest_flattened(): client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -20963,40 +21098,37 @@ def test_list_reactions_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.ListReactionsResponse() + return_value = None # get arguments that satisfy an http rule for this method - sample_request = {"parent": "spaces/sample1/messages/sample2"} + sample_request = {"name": "spaces/sample1"} # get truthy value for each flattened field mock_args = dict( - parent="parent_value", + name="name_value", ) mock_args.update(sample_request) # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 - # Convert return value to protobuf type - return_value = 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"} - client.list_reactions(**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/{parent=spaces/*/messages/*}/reactions" % client.transport._host, - args[1], + "%s/v1/{name=spaces/*}" % client.transport._host, args[1] ) -def test_list_reactions_rest_flattened_error(transport: str = "rest"): +def test_delete_space_rest_flattened_error(transport: str = "rest"): client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -21005,74 +21137,13 @@ def test_list_reactions_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_reactions( - reaction.ListReactionsRequest(), - parent="parent_value", - ) - - -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(), - ], - ), + client.delete_space( + space.DeleteSpaceRequest(), + name="name_value", ) - # 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(): +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: @@ -21086,30 +21157,35 @@ 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.complete_import_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.complete_import_space] = ( + mock_rpc + ) request = {} - client.delete_reaction(request) + client.complete_import_space(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.delete_reaction(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_delete_reaction_rest_required_fields( - request_type=reaction.DeleteReactionRequest, +def test_complete_import_space_rest_required_fields( + request_type=space.CompleteImportSpaceRequest, ): transport_class = transports.ChatServiceRestTransport @@ -21125,7 +21201,7 @@ def test_delete_reaction_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).delete_reaction._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 @@ -21134,7 +21210,7 @@ def test_delete_reaction_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).delete_reaction._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 @@ -21148,7 +21224,7 @@ def test_delete_reaction_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = None + 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 @@ -21160,91 +21236,40 @@ def test_delete_reaction_rest_required_fields( pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "delete", + "method": "post", "query_params": pb_request, } + transcode_result["body"] = pb_request transcode.return_value = transcode_result response_value = Response() response_value.status_code = 200 - json_return_value = "" + + # Convert return value to protobuf type + 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.delete_reaction(request) + response = client.complete_import_space(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert sorted(expected_params) == sorted(actual_params) -def test_delete_reaction_rest_unset_required_fields(): +def test_complete_import_space_rest_unset_required_fields(): transport = transports.ChatServiceRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.delete_reaction._get_unset_required_fields({}) + unset_fields = transport.complete_import_space._get_unset_required_fields({}) assert set(unset_fields) == (set(()) & set(("name",))) -def test_delete_reaction_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/reactions/sample3"} - - # get truthy value for each flattened field - mock_args = dict( - name="name_value", - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = "" - response_value._content = 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_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/*/messages/*/reactions/*}" % client.transport._host, - args[1], - ) - - -def test_delete_reaction_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_reaction( - reaction.DeleteReactionRequest(), - name="name_value", - ) - - -def test_create_custom_emoji_rest_use_cached_wrapped_rpc(): +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: @@ -21259,7 +21284,7 @@ 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.find_direct_message in client._transport._wrapped_methods ) # Replace cached wrapped function with mock @@ -21267,29 +21292,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.find_direct_message] = ( mock_rpc ) request = {} - client.create_custom_emoji(request) + client.find_direct_message(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.create_custom_emoji(request) + 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_create_custom_emoji_rest_required_fields( - request_type=reaction.CreateCustomEmojiRequest, +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( @@ -21297,20 +21323,29 @@ def test_create_custom_emoji_rest_required_fields( ) # verify fields with default values are dropped + assert "name" not in jsonified_request unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).create_custom_emoji._get_unset_required_fields(jsonified_request) + ).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() - ).create_custom_emoji._get_unset_required_fields(jsonified_request) + ).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" client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -21319,7 +21354,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.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 @@ -21331,96 +21366,144 @@ def test_create_custom_emoji_rest_required_fields( pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "post", + "method": "get", "query_params": pb_request, } - transcode_result["body"] = pb_request transcode.return_value = transcode_result response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = reaction.CustomEmoji.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_custom_emoji(request) + response = client.find_direct_message(request) - expected_params = [("$alt", "json;enum-encoding=int")] + expected_params = [ + ( + "name", + "", + ), + ("$alt", "json;enum-encoding=int"), + ] actual_params = req.call_args.kwargs["params"] assert sorted(expected_params) == sorted(actual_params) -def test_create_custom_emoji_rest_unset_required_fields(): +def test_find_direct_message_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.find_direct_message._get_unset_required_fields({}) + assert set(unset_fields) == (set(("name",)) & set(("name",))) -def test_create_custom_emoji_rest_flattened(): - client = ChatServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) +def test_find_group_chats_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached 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_group_chats 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_group_chats] = ( + 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_group_chats(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_group_chats(request) + + # Establish 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_flattened_error(transport: str = "rest"): +def test_find_group_chats_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_custom_emoji( - reaction.CreateCustomEmojiRequest(), - custom_emoji=reaction.CustomEmoji(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.FindGroupChatsResponse( + spaces=[ + space.Space(), + space.Space(), + space.Space(), + ], + next_page_token="abc", + ), + space.FindGroupChatsResponse( + spaces=[], + next_page_token="def", + ), + space.FindGroupChatsResponse( + spaces=[ + space.Space(), + ], + next_page_token="ghi", + ), + space.FindGroupChatsResponse( + spaces=[ + space.Space(), + space.Space(), + ], + ), ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(space.FindGroupChatsResponse.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 = {} -def test_get_custom_emoji_rest_use_cached_wrapped_rpc(): + pager = client.find_group_chats(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, space.Space) for i in results) + + pages = list(client.find_group_chats(request=sample_request).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +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: @@ -21434,37 +21517,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( @@ -21475,21 +21558,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(), @@ -21498,7 +21583,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 @@ -21510,39 +21595,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 sorted(expected_params) == sorted(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", @@ -21551,14 +21645,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) @@ -21566,24 +21661,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, @@ -21592,114 +21687,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", - ) - - -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: - 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_custom_emojis in client._transport._wrapped_methods - ) - - # Replace cached wrapped function with mock - mock_rpc = 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] = ( - mock_rpc - ) - - request = {} - client.list_custom_emojis(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - 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_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(), - ], - ), + client.create_membership( + gc_membership.CreateMembershipRequest(), + parent="parent_value", + membership=gc_membership.Membership(name="name_value"), ) - # 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(): +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: @@ -21713,39 +21708,36 @@ def test_delete_custom_emoji_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert ( - client._transport.delete_custom_emoji 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.delete_custom_emoji] = ( + client._transport._wrapped_methods[client._transport.update_membership] = ( mock_rpc ) request = {} - client.delete_custom_emoji(request) + client.update_membership(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.delete_custom_emoji(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_delete_custom_emoji_rest_required_fields( - request_type=reaction.DeleteCustomEmojiRequest, +def test_update_membership_rest_required_fields( + request_type=gc_membership.UpdateMembershipRequest, ): transport_class = transports.ChatServiceRestTransport request_init = {} - request_init["name"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -21756,21 +21748,24 @@ def test_delete_custom_emoji_rest_required_fields( 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(), @@ -21779,7 +21774,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 @@ -21791,36 +21786,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 sorted(expected_params) == sorted(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", @@ -21829,37 +21841,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, @@ -21868,13 +21884,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: @@ -21888,34 +21905,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 @@ -21931,7 +21946,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 @@ -21940,7 +21955,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 @@ -21954,7 +21971,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 @@ -21966,7 +21983,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 @@ -21975,30 +21992,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 sorted(expected_params) == sorted(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", @@ -22007,10 +22024,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( @@ -22022,25 +22039,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, @@ -22049,13 +22065,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: @@ -22069,39 +22085,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( @@ -22112,19 +22124,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(), @@ -22133,7 +22147,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 @@ -22145,7 +22159,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 @@ -22155,38 +22169,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 sorted(expected_params) == sorted(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", @@ -22195,17 +22209,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) @@ -22213,26 +22225,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, @@ -22241,14 +22252,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: @@ -22262,40 +22273,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( @@ -22306,21 +22312,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(), @@ -22329,7 +22343,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 @@ -22350,30 +22364,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 sorted(expected_params) == sorted(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", @@ -22382,16 +22405,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) @@ -22399,26 +22420,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, @@ -22427,13 +22447,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: @@ -22447,30 +22528,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 @@ -22486,7 +22567,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 @@ -22495,7 +22576,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 @@ -22509,7 +22590,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 @@ -22521,39 +22602,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 sorted(expected_params) == sorted(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", @@ -22562,10 +22640,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( @@ -22576,25 +22654,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, @@ -22603,13 +22680,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: @@ -22623,38 +22700,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( @@ -22662,38 +22739,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(), @@ -22702,7 +22761,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 @@ -22714,59 +22773,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 sorted(expected_params) == sorted(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", @@ -22775,15 +22815,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) @@ -22791,24 +22830,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, @@ -22817,77 +22856,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: @@ -22901,35 +22876,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 @@ -22945,7 +22917,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 @@ -22954,7 +22926,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 @@ -22968,7 +22940,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 @@ -22989,34 +22961,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 sorted(expected_params) == sorted(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", @@ -23025,12 +22993,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( @@ -23042,28 +23008,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, @@ -23072,13 +23034,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: @@ -23093,8 +23055,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 @@ -23102,29 +23063,131 @@ 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, +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( @@ -23135,19 +23198,21 @@ def test_update_space_notification_setting_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).update_space_notification_setting._get_unset_required_fields(jsonified_request) + ).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() - ).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",)) + ).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(), @@ -23156,7 +23221,7 @@ def test_update_space_notification_setting_rest_required_fields( 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 @@ -23168,52 +23233,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 sorted(expected_params) == sorted(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", @@ -23222,52 +23271,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, @@ -23276,16 +23310,13 @@ 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_create_section_rest_use_cached_wrapped_rpc(): +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: @@ -23299,35 +23330,39 @@ def test_create_section_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.create_section in client._transport._wrapped_methods + assert ( + client._transport.get_space_read_state in client._transport._wrapped_methods + ) # Replace cached wrapped function with mock mock_rpc = 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_section] = mock_rpc + client._transport._wrapped_methods[client._transport.get_space_read_state] = ( + mock_rpc + ) request = {} - client.create_section(request) + client.get_space_read_state(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.create_section(request) + client.get_space_read_state(request) # Establish 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_section_rest_required_fields( - request_type=gc_section.CreateSectionRequest, +def test_get_space_read_state_rest_required_fields( + request_type=space_read_state.GetSpaceReadStateRequest, ): transport_class = transports.ChatServiceRestTransport request_init = {} - request_init["parent"] = "" + request_init["name"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -23338,21 +23373,21 @@ def test_create_section_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).create_section._get_unset_required_fields(jsonified_request) + ).get_space_read_state._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present - jsonified_request["parent"] = "parent_value" + jsonified_request["name"] = "name_value" unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).create_section._get_unset_required_fields(jsonified_request) + ).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 "parent" in jsonified_request - assert jsonified_request["parent"] == "parent_value" + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -23361,7 +23396,7 @@ def test_create_section_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = gc_section.Section() + 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 @@ -23373,48 +23408,39 @@ def test_create_section_rest_required_fields( pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "post", + "method": "get", "query_params": pb_request, } - transcode_result["body"] = pb_request transcode.return_value = transcode_result response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = gc_section.Section.pb(return_value) + 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.create_section(request) + response = client.get_space_read_state(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert sorted(expected_params) == sorted(actual_params) -def test_create_section_rest_unset_required_fields(): +def test_get_space_read_state_rest_unset_required_fields(): transport = transports.ChatServiceRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.create_section._get_unset_required_fields({}) - assert set(unset_fields) == ( - set(()) - & set( - ( - "parent", - "section", - ) - ) - ) + unset_fields = transport.get_space_read_state._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) -def test_create_section_rest_flattened(): +def test_get_space_read_state_rest_flattened(): client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -23423,15 +23449,14 @@ def test_create_section_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_section.Section() + return_value = space_read_state.SpaceReadState() # get arguments that satisfy an http rule for this method - sample_request = {"parent": "users/sample1"} + sample_request = {"name": "users/sample1/spaces/sample2/spaceReadState"} # get truthy value for each flattened field mock_args = dict( - parent="parent_value", - section=gc_section.Section(name="name_value"), + name="name_value", ) mock_args.update(sample_request) @@ -23439,24 +23464,25 @@ def test_create_section_rest_flattened(): response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = gc_section.Section.pb(return_value) + 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"} - client.create_section(**mock_args) + client.get_space_read_state(**mock_args) # Establish that the underlying call was 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] + "%s/v1/{name=users/*/spaces/*/spaceReadState}" % client.transport._host, + args[1], ) -def test_create_section_rest_flattened_error(transport: str = "rest"): +def test_get_space_read_state_rest_flattened_error(transport: str = "rest"): client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -23465,14 +23491,13 @@ def test_create_section_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_section( - gc_section.CreateSectionRequest(), - parent="parent_value", - section=gc_section.Section(name="name_value"), + client.get_space_read_state( + space_read_state.GetSpaceReadStateRequest(), + name="name_value", ) -def test_delete_section_rest_use_cached_wrapped_rpc(): +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: @@ -23486,33 +23511,39 @@ def test_delete_section_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.delete_section in client._transport._wrapped_methods + assert ( + client._transport.update_space_read_state + in client._transport._wrapped_methods + ) # Replace cached wrapped function with mock mock_rpc = 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 + client._transport._wrapped_methods[ + client._transport.update_space_read_state + ] = mock_rpc request = {} - client.delete_section(request) + client.update_space_read_state(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.delete_section(request) + client.update_space_read_state(request) # Establish 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_section_rest_required_fields(request_type=section.DeleteSectionRequest): +def test_update_space_read_state_rest_required_fields( + request_type=gc_space_read_state.UpdateSpaceReadStateRequest, +): transport_class = transports.ChatServiceRestTransport request_init = {} - request_init["name"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -23523,21 +23554,19 @@ def test_delete_section_rest_required_fields(request_type=section.DeleteSectionR unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).delete_section._get_unset_required_fields(jsonified_request) + ).update_space_read_state._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_section._get_unset_required_fields(jsonified_request) + ).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 - assert "name" in jsonified_request - assert jsonified_request["name"] == "name_value" client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -23546,7 +23575,7 @@ def test_delete_section_rest_required_fields(request_type=section.DeleteSectionR request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = None + 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 @@ -23558,36 +23587,48 @@ def test_delete_section_rest_required_fields(request_type=section.DeleteSectionR 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_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_section(request) + response = client.update_space_read_state(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert sorted(expected_params) == sorted(actual_params) -def test_delete_section_rest_unset_required_fields(): +def test_update_space_read_state_rest_unset_required_fields(): transport = transports.ChatServiceRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.delete_section._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name",))) + unset_fields = transport.update_space_read_state._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(("updateMask",)) + & set( + ( + "spaceReadState", + "updateMask", + ) + ) + ) -def test_delete_section_rest_flattened(): +def test_update_space_read_state_rest_flattened(): client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -23596,37 +23637,44 @@ def test_delete_section_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_space_read_state.SpaceReadState() # get arguments that satisfy an http rule for this method - sample_request = {"name": "users/sample1/sections/sample2"} + sample_request = { + "space_read_state": {"name": "users/sample1/spaces/sample2/spaceReadState"} + } # get truthy value for each flattened field mock_args = dict( - name="name_value", + 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) # 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_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"} - client.delete_section(**mock_args) + client.update_space_read_state(**mock_args) # Establish that the underlying call was 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] + "%s/v1/{space_read_state.name=users/*/spaces/*/spaceReadState}" + % client.transport._host, + args[1], ) -def test_delete_section_rest_flattened_error(transport: str = "rest"): +def test_update_space_read_state_rest_flattened_error(transport: str = "rest"): client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -23635,13 +23683,14 @@ def test_delete_section_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_section( - section.DeleteSectionRequest(), - name="name_value", + 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"]), ) -def test_update_section_rest_use_cached_wrapped_rpc(): +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: @@ -23655,34 +23704,40 @@ def test_update_section_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.update_section in client._transport._wrapped_methods + assert ( + client._transport.get_thread_read_state + in client._transport._wrapped_methods + ) # Replace cached wrapped function with mock mock_rpc = 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_section] = mock_rpc + client._transport._wrapped_methods[client._transport.get_thread_read_state] = ( + mock_rpc + ) request = {} - client.update_section(request) + client.get_thread_read_state(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.update_section(request) + client.get_thread_read_state(request) # Establish 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_section_rest_required_fields( - request_type=gc_section.UpdateSectionRequest, +def test_get_thread_read_state_rest_required_fields( + request_type=thread_read_state.GetThreadReadStateRequest, ): transport_class = transports.ChatServiceRestTransport request_init = {} + request_init["name"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -23693,19 +23748,21 @@ def test_update_section_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).update_section._get_unset_required_fields(jsonified_request) + ).get_thread_read_state._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_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",)) + ).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" client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -23714,7 +23771,7 @@ def test_update_section_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = gc_section.Section() + 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 @@ -23726,48 +23783,39 @@ def test_update_section_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_section.Section.pb(return_value) + 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.update_section(request) + response = client.get_thread_read_state(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert sorted(expected_params) == sorted(actual_params) -def test_update_section_rest_unset_required_fields(): +def test_get_thread_read_state_rest_unset_required_fields(): transport = transports.ChatServiceRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.update_section._get_unset_required_fields({}) - assert set(unset_fields) == ( - set(("updateMask",)) - & set( - ( - "section", - "updateMask", - ) - ) - ) + unset_fields = transport.get_thread_read_state._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) -def test_update_section_rest_flattened(): +def test_get_thread_read_state_rest_flattened(): client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -23776,15 +23824,16 @@ def test_update_section_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_section.Section() + return_value = thread_read_state.ThreadReadState() # get arguments that satisfy an http rule for this method - sample_request = {"section": {"name": "users/sample1/sections/sample2"}} + sample_request = { + "name": "users/sample1/spaces/sample2/threads/sample3/threadReadState" + } # 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"]), + name="name_value", ) mock_args.update(sample_request) @@ -23792,24 +23841,26 @@ def test_update_section_rest_flattened(): response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = gc_section.Section.pb(return_value) + 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.update_section(**mock_args) + client.get_thread_read_state(**mock_args) # Establish that the underlying call was 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] + "%s/v1/{name=users/*/spaces/*/threads/*/threadReadState}" + % client.transport._host, + args[1], ) -def test_update_section_rest_flattened_error(transport: str = "rest"): +def test_get_thread_read_state_rest_flattened_error(transport: str = "rest"): client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -23818,14 +23869,13 @@ def test_update_section_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_section( - gc_section.UpdateSectionRequest(), - section=gc_section.Section(name="name_value"), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + client.get_thread_read_state( + thread_read_state.GetThreadReadStateRequest(), + name="name_value", ) -def test_list_sections_rest_use_cached_wrapped_rpc(): +def test_get_availability_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -23839,33 +23889,37 @@ def test_list_sections_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.list_sections in client._transport._wrapped_methods + assert client._transport.get_availability in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = 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 + client._transport._wrapped_methods[client._transport.get_availability] = ( + mock_rpc + ) request = {} - client.list_sections(request) + client.get_availability(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.list_sections(request) + client.get_availability(request) # Establish 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): +def test_get_availability_rest_required_fields( + request_type=availability.GetAvailabilityRequest, +): transport_class = transports.ChatServiceRestTransport request_init = {} - request_init["parent"] = "" + request_init["name"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -23876,28 +23930,21 @@ def test_list_sections_rest_required_fields(request_type=section.ListSectionsReq unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).list_sections._get_unset_required_fields(jsonified_request) + ).get_availability._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present - jsonified_request["parent"] = "parent_value" + jsonified_request["name"] = "name_value" unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).list_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", - ) - ) + ).get_availability._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == "parent_value" + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -23906,7 +23953,7 @@ def test_list_sections_rest_required_fields(request_type=section.ListSectionsReq request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = section.ListSectionsResponse() + return_value = availability.Availability() # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values @@ -23927,38 +23974,30 @@ def test_list_sections_rest_required_fields(request_type=section.ListSectionsReq response_value.status_code = 200 # Convert return value to protobuf type - return_value = section.ListSectionsResponse.pb(return_value) + return_value = availability.Availability.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_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) + response = client.get_availability(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert sorted(expected_params) == sorted(actual_params) -def test_list_sections_rest_unset_required_fields(): +def test_get_availability_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",)) - ) + unset_fields = transport.get_availability._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) -def test_list_sections_rest_flattened(): +def test_get_availability_rest_flattened(): client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -23967,14 +24006,14 @@ def test_list_sections_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 = section.ListSectionsResponse() + return_value = availability.Availability() # get arguments that satisfy an http rule for this method - sample_request = {"parent": "users/sample1"} + sample_request = {"name": "users/sample1/availability"} # get truthy value for each flattened field mock_args = dict( - parent="parent_value", + name="name_value", ) mock_args.update(sample_request) @@ -23982,24 +24021,24 @@ def test_list_sections_rest_flattened(): response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = section.ListSectionsResponse.pb(return_value) + return_value = availability.Availability.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = 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_sections(**mock_args) + client.get_availability(**mock_args) # Establish that the underlying call was 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] + "%s/v1/{name=users/*/availability}" % client.transport._host, args[1] ) -def test_list_sections_rest_flattened_error(transport: str = "rest"): +def test_get_availability_rest_flattened_error(transport: str = "rest"): client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -24008,74 +24047,13 @@ def test_list_sections_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_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(), - ], - 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(), - ], - ), + client.get_availability( + availability.GetAvailabilityRequest(), + name="name_value", ) - # 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(): +def test_mark_as_active_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -24089,32 +24067,30 @@ def test_position_section_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.position_section in client._transport._wrapped_methods + assert client._transport.mark_as_active in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = 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 - ) + client._transport._wrapped_methods[client._transport.mark_as_active] = mock_rpc request = {} - client.position_section(request) + client.mark_as_active(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.position_section(request) + client.mark_as_active(request) # Establish 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, +def test_mark_as_active_rest_required_fields( + request_type=availability.MarkAsActiveRequest, ): transport_class = transports.ChatServiceRestTransport @@ -24130,7 +24106,7 @@ def test_position_section_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).position_section._get_unset_required_fields(jsonified_request) + ).mark_as_active._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present @@ -24139,7 +24115,7 @@ def test_position_section_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).position_section._get_unset_required_fields(jsonified_request) + ).mark_as_active._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone @@ -24153,7 +24129,7 @@ def test_position_section_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = section.PositionSectionResponse() + return_value = availability.Availability() # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values @@ -24175,30 +24151,149 @@ def test_position_section_rest_required_fields( response_value.status_code = 200 # Convert return value to protobuf type - return_value = section.PositionSectionResponse.pb(return_value) + return_value = availability.Availability.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_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) + response = client.mark_as_active(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert sorted(expected_params) == sorted(actual_params) -def test_position_section_rest_unset_required_fields(): +def test_mark_as_active_rest_unset_required_fields(): transport = transports.ChatServiceRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.position_section._get_unset_required_fields({}) + unset_fields = transport.mark_as_active._get_unset_required_fields({}) assert set(unset_fields) == (set(()) & set(("name",))) -def test_list_section_items_rest_use_cached_wrapped_rpc(): +def test_mark_as_away_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached 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.mark_as_away in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.mark_as_away] = mock_rpc + + request = {} + client.mark_as_away(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.mark_as_away(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_mark_as_away_rest_required_fields(request_type=availability.MarkAsAwayRequest): + 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() + ).mark_as_away._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() + ).mark_as_away._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 = availability.Availability() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force 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 = availability.Availability.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.mark_as_away(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_mark_as_away_rest_unset_required_fields(): + transport = transports.ChatServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.mark_as_away._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) + + +def test_mark_as_do_not_disturb_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -24213,7 +24308,8 @@ def test_list_section_items_rest_use_cached_wrapped_rpc(): # Ensure method has been cached assert ( - client._transport.list_section_items in client._transport._wrapped_methods + client._transport.mark_as_do_not_disturb + in client._transport._wrapped_methods ) # Replace cached wrapped function with mock @@ -24221,30 +24317,30 @@ def test_list_section_items_rest_use_cached_wrapped_rpc(): mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.list_section_items] = ( + client._transport._wrapped_methods[client._transport.mark_as_do_not_disturb] = ( mock_rpc ) request = {} - client.list_section_items(request) + client.mark_as_do_not_disturb(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.list_section_items(request) + client.mark_as_do_not_disturb(request) # Establish 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, +def test_mark_as_do_not_disturb_rest_required_fields( + request_type=availability.MarkAsDoNotDisturbRequest, ): transport_class = transports.ChatServiceRestTransport request_init = {} - request_init["parent"] = "" + request_init["name"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -24255,29 +24351,143 @@ def test_list_section_items_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).list_section_items._get_unset_required_fields(jsonified_request) + ).mark_as_do_not_disturb._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present - jsonified_request["parent"] = "parent_value" + jsonified_request["name"] = "name_value" unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).list_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", + ).mark_as_do_not_disturb._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 = availability.Availability() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force 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 = availability.Availability.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.mark_as_do_not_disturb(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_mark_as_do_not_disturb_rest_unset_required_fields(): + transport = transports.ChatServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.mark_as_do_not_disturb._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) + + +def test_update_availability_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached 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.update_availability in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = 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_availability] = ( + mock_rpc ) + + request = {} + client.update_availability(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_availability(request) + + # Establish 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_availability_rest_required_fields( + request_type=gc_availability.UpdateAvailabilityRequest, +): + 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_availability._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_availability._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 - assert "parent" in jsonified_request - assert jsonified_request["parent"] == "parent_value" client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -24286,7 +24496,7 @@ def test_list_section_items_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = section.ListSectionItemsResponse() + return_value = gc_availability.Availability() # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values @@ -24298,48 +24508,48 @@ def test_list_section_items_rest_required_fields( pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "get", + "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 = section.ListSectionItemsResponse.pb(return_value) + return_value = gc_availability.Availability.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_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) + response = client.update_availability(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert sorted(expected_params) == sorted(actual_params) -def test_list_section_items_rest_unset_required_fields(): +def test_update_availability_rest_unset_required_fields(): transport = transports.ChatServiceRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.list_section_items._get_unset_required_fields({}) + unset_fields = transport.update_availability._get_unset_required_fields({}) assert set(unset_fields) == ( - set( + set(("updateMask",)) + & set( ( - "filter", - "pageSize", - "pageToken", + "availability", + "updateMask", ) ) - & set(("parent",)) ) -def test_list_section_items_rest_flattened(): +def test_update_availability_rest_flattened(): client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -24348,14 +24558,15 @@ def test_list_section_items_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 = section.ListSectionItemsResponse() + return_value = gc_availability.Availability() # get arguments that satisfy an http rule for this method - sample_request = {"parent": "users/sample1/sections/sample2"} + sample_request = {"availability": {"name": "users/sample1/availability"}} # get truthy value for each flattened field mock_args = dict( - parent="parent_value", + availability=gc_availability.Availability(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) mock_args.update(sample_request) @@ -24363,24 +24574,25 @@ def test_list_section_items_rest_flattened(): response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = section.ListSectionItemsResponse.pb(return_value) + return_value = gc_availability.Availability.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = 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) + client.update_availability(**mock_args) # Establish that the underlying call was 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] + "%s/v1/{availability.name=users/*/availability}" % client.transport._host, + args[1], ) -def test_list_section_items_rest_flattened_error(transport: str = "rest"): +def test_update_availability_rest_flattened_error(transport: str = "rest"): client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -24389,74 +24601,14 @@ def test_list_section_items_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_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(), - ], - ), + client.update_availability( + gc_availability.UpdateAvailabilityRequest(), + availability=gc_availability.Availability(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) - # 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(): +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: @@ -24470,38 +24622,35 @@ def test_move_section_item_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.move_section_item in client._transport._wrapped_methods + assert client._transport.get_space_event in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = 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 - ) + client._transport._wrapped_methods[client._transport.get_space_event] = mock_rpc request = {} - client.move_section_item(request) + client.get_space_event(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.move_section_item(request) + client.get_space_event(request) # Establish 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, +def test_get_space_event_rest_required_fields( + request_type=space_event.GetSpaceEventRequest, ): 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( @@ -24512,24 +24661,21 @@ def test_move_section_item_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).move_section_item._get_unset_required_fields(jsonified_request) + ).get_space_event._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) + ).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" - assert "targetSection" in jsonified_request - assert jsonified_request["targetSection"] == "target_section_value" client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -24538,7 +24684,7 @@ def test_move_section_item_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = section.MoveSectionItemResponse() + 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 @@ -24550,48 +24696,39 @@ def test_move_section_item_rest_required_fields( pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "post", + "method": "get", "query_params": pb_request, } - transcode_result["body"] = pb_request transcode.return_value = transcode_result response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = section.MoveSectionItemResponse.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.move_section_item(request) + response = client.get_space_event(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert sorted(expected_params) == sorted(actual_params) -def test_move_section_item_rest_unset_required_fields(): +def test_get_space_event_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", - ) - ) - ) + unset_fields = transport.get_space_event._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) -def test_move_section_item_rest_flattened(): +def test_get_space_event_rest_flattened(): client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -24600,15 +24737,14 @@ def test_move_section_item_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 = section.MoveSectionItemResponse() + return_value = space_event.SpaceEvent() # get arguments that satisfy an http rule for this method - sample_request = {"name": "users/sample1/sections/sample2/items/sample3"} + sample_request = {"name": "spaces/sample1/spaceEvents/sample2"} # get truthy value for each flattened field mock_args = dict( name="name_value", - target_section="target_section_value", ) mock_args.update(sample_request) @@ -24616,25 +24752,24 @@ def test_move_section_item_rest_flattened(): response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = section.MoveSectionItemResponse.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"} - client.move_section_item(**mock_args) + client.get_space_event(**mock_args) # Establish that the underlying call was 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], + "%s/v1/{name=spaces/*/spaceEvents/*}" % client.transport._host, args[1] ) -def test_move_section_item_rest_flattened_error(transport: str = "rest"): +def test_get_space_event_rest_flattened_error(transport: str = "rest"): client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -24643,2286 +24778,4569 @@ def test_move_section_item_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.move_section_item( - section.MoveSectionItemRequest(), + client.get_space_event( + space_event.GetSpaceEventRequest(), 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): +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=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.list_space_events 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() + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. ) - - # It is an error to provide scopes and a transport instance. - transport = transports.ChatServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = ChatServiceClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, + client._transport._wrapped_methods[client._transport.list_space_events] = ( + mock_rpc ) + request = {} + client.list_space_events(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.list_space_events(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_list_space_events_rest_required_fields( + request_type=space_event.ListSpaceEventsRequest, +): + 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["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 -def test_transport_kind_grpc(): - transport = ChatServiceClient.get_transport_class("grpc")( + unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ) - assert transport.kind == "grpc" + ).list_space_events._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" -def test_initialize_client_w_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) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "filter", + "page_size", + "page_token", + ) ) - assert client is not None + 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_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) + # 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 = gc_message.CreateMessageRequest() - assert args[0] == request_msg + 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) -# This 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", - ) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.list_messages), "__call__") as call: - call.return_value = message.ListMessagesResponse() - client.list_messages(request=None) + response = client.list_space_events(request) - # 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 + expected_params = [ + ( + "filter", + "", + ), + ("$alt", "json;enum-encoding=int"), + ] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_list_memberships_empty_call_grpc(): - client = ChatServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", +def test_list_space_events_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.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_get_membership_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.get_membership), "__call__") as call: - call.return_value = membership.Membership() - client.get_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 = space_event.ListSpaceEventsResponse() - # 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 + # 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) -# This 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", - ) + # 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"} - # 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) + client.list_space_events(**mock_args) - # 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 + # Establish that the underlying call was 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] + ) -# This 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_list_space_events_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.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. -def test_delete_message_empty_call_grpc(): +def test_list_space_events_rest_pager(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_message), "__call__") as call: - call.return_value = None - client.delete_message(request=None) + # 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 - # 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 + # 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 + sample_request = {"parent": "spaces/sample1"} -# This 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", - ) + pager = client.list_space_events(request=sample_request) - # 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) + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, space_event.SpaceEvent) for i in results) - # 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 + 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 -# This 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", - ) +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", + ) - # 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) + # 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 = attachment.UploadAttachmentRequest() - assert args[0] == request_msg + # Ensure method has been cached + assert ( + client._transport.get_space_notification_setting + in client._transport._wrapped_methods + ) + # Replace cached wrapped function with mock + mock_rpc = 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 -# This 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", - ) + request = {} + client.get_space_notification_setting(request) - # 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 gRPC stub method was called. + assert mock_rpc.call_count == 1 - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = space.ListSpacesRequest() - assert args[0] == request_msg + client.get_space_notification_setting(request) + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_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) +def test_get_space_notification_setting_rest_required_fields( + request_type=space_notification_setting.GetSpaceNotificationSettingRequest, +): + transport_class = transports.ChatServiceRestTransport - # 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 + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + # verify fields with default values are dropped -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_get_space_empty_call_grpc(): - client = ChatServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get_space_notification_setting._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), "__call__") as call: - call.return_value = space.Space() - client.get_space(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 = space.GetSpaceRequest() - assert args[0] == request_msg + jsonified_request["name"] = "name_value" + + 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" -# This 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", + 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: - call.return_value = gc_space.Space() - client.create_space(request=None) + # 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 - # 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 + 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. -def test_set_up_space_empty_call_grpc(): - client = ChatServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.set_up_space), "__call__") as call: - call.return_value = space.Space() - client.set_up_space(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 = space_setup.SetUpSpaceRequest() - assert args[0] == request_msg + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_update_space_empty_call_grpc(): - client = ChatServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", +def test_get_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.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 + unset_fields = transport.get_space_notification_setting._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_delete_space_empty_call_grpc(): +def test_get_space_notification_setting_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.delete_space), "__call__") as call: - call.return_value = None - client.delete_space(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_notification_setting.SpaceNotificationSetting() - # 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 + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "users/sample1/spaces/sample2/spaceNotificationSetting" + } + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + ) + mock_args.update(sample_request) -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_complete_import_space_empty_call_grpc(): - client = ChatServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = 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"} - # 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) + client.get_space_notification_setting(**mock_args) - # 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 + # Establish that the underlying call was 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. -def test_find_direct_message_empty_call_grpc(): +def test_get_space_notification_setting_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.find_direct_message), "__call__" - ) as call: - call.return_value = space.Space() - client.find_direct_message(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_notification_setting( + space_notification_setting.GetSpaceNotificationSettingRequest(), + name="name_value", + ) - # 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 +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. -def test_find_group_chats_empty_call_grpc(): - client = ChatServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() - # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.find_group_chats), "__call__") as call: - call.return_value = space.FindGroupChatsResponse() - client.find_group_chats(request=None) + # Ensure method has been cached + assert ( + client._transport.update_space_notification_setting + in client._transport._wrapped_methods + ) - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = space.FindGroupChatsRequest() - 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_notification_setting + ] = mock_rpc + + 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. -def test_create_membership_empty_call_grpc(): - client = ChatServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) + client.update_space_notification_setting(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) + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = gc_membership.CreateMembershipRequest() - 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. -def test_update_membership_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.update_membership), "__call__" - ) as call: - call.return_value = gc_membership.Membership() - client.update_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 = gc_membership.UpdateMembershipRequest() - assert args[0] == request_msg + 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 -# This 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", + transport="rest", ) + request = request_type(**request_init) - # 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) + # 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 - # 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 + 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) -# This 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", - ) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.create_reaction), "__call__") as call: - call.return_value = gc_reaction.Reaction() - client.create_reaction(request=None) + response = client.update_space_notification_setting(request) - # 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 + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_list_reactions_empty_call_grpc(): - client = ChatServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", +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.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 + unset_fields = ( + transport.update_space_notification_setting._get_unset_required_fields({}) + ) + assert set(unset_fields) == ( + set(("updateMask",)) + & set( + ( + "spaceNotificationSetting", + "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_delete_reaction_empty_call_grpc(): +def test_update_space_notification_setting_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.delete_reaction), "__call__") as call: - call.return_value = None - client.delete_reaction(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 = gc_space_notification_setting.SpaceNotificationSetting() - # 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 + # get arguments that satisfy an http rule for this method + sample_request = { + "space_notification_setting": { + "name": "users/sample1/spaces/sample2/spaceNotificationSetting" + } + } + # 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"]), + ) + mock_args.update(sample_request) -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_create_custom_emoji_empty_call_grpc(): - client = ChatServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = 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"} - # 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) + client.update_space_notification_setting(**mock_args) - # 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 + # Establish that the underlying call was 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], + ) -# This 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(): +def test_update_space_notification_setting_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_custom_emoji), "__call__") as call: - call.return_value = reaction.CustomEmoji() - client.get_custom_emoji(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 = reaction.GetCustomEmojiRequest() - 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", + ) -# This 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", - ) + # 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_custom_emojis), "__call__" - ) as call: - call.return_value = reaction.ListCustomEmojisResponse() - client.list_custom_emojis(request=None) + # Ensure method has been cached + assert client._transport.create_section in client._transport._wrapped_methods - # 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 + # Replace cached wrapped function with mock + mock_rpc = 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_section] = mock_rpc + request = {} + 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. -def test_delete_custom_emoji_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_custom_emoji), "__call__" - ) as call: - call.return_value = None - client.delete_custom_emoji(request=None) + client.create_section(request) - # 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 + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_get_space_read_state_empty_call_grpc(): - client = ChatServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", +def test_create_section_rest_required_fields( + request_type=gc_section.CreateSectionRequest, +): + 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) ) - # 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) + # 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_read_state.GetSpaceReadStateRequest() - 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 default values are now present + + jsonified_request["parent"] = "parent_value" + + 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. -def test_update_space_read_state_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.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 + # 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 + 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_get_thread_read_state_empty_call_grpc(): - client = ChatServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) + # Convert return value to protobuf type + return_value = gc_section.Section.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.get_thread_read_state), "__call__" - ) as call: - call.return_value = thread_read_state.ThreadReadState() - client.get_thread_read_state(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 = thread_read_state.GetThreadReadStateRequest() - assert args[0] == request_msg + response = client.create_section(request) + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_get_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) +def test_create_section_rest_unset_required_fields(): + transport = transports.ChatServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) - # 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 + unset_fields = transport.create_section._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(()) + & set( + ( + "parent", + "section", + ) + ) + ) -# This 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(): +def test_create_section_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_space_events), "__call__" - ) as call: - call.return_value = space_event.ListSpaceEventsResponse() - client.list_space_events(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 = gc_section.Section() - # 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 + # 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", + section=gc_section.Section(name="name_value"), + ) + mock_args.update(sample_request) -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_get_space_notification_setting_empty_call_grpc(): - client = ChatServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = 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"} - # 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) + client.create_section(**mock_args) - # 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 + # Establish that the underlying call was 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. -def test_update_space_notification_setting_empty_call_grpc(): +def test_create_section_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_space_notification_setting), "__call__" - ) as call: - call.return_value = gc_space_notification_setting.SpaceNotificationSetting() - client.update_space_notification_setting(request=None) + # 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"), + ) - # 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_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", ) - assert args[0] == request_msg + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_create_section_empty_call_grpc(): - client = ChatServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) + # 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.create_section), "__call__") as call: - call.return_value = gc_section.Section() - client.create_section(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 = gc_section.CreateSectionRequest() - assert args[0] == request_msg + request = {} + client.delete_section(request) + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_delete_section_empty_call_grpc(): - client = ChatServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) + client.delete_section(request) - # 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 a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = section.DeleteSectionRequest() - assert args[0] == request_msg +def test_delete_section_rest_required_fields(request_type=section.DeleteSectionRequest): + 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_update_section_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.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 + # verify fields with default values are dropped + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).delete_section._get_unset_required_fields(jsonified_request) + 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. -def test_list_sections_empty_call_grpc(): - client = ChatServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) + # verify required fields with default values are now present - # 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) + jsonified_request["name"] = "name_value" - # 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 + 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. -def test_position_section_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.position_section), "__call__") as call: - call.return_value = section.PositionSectionResponse() - client.position_section(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 = section.PositionSectionRequest() - assert args[0] == request_msg + 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"} -# This 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", - ) + response = client.delete_section(request) - # 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) + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = section.ListSectionItemsRequest() - assert args[0] == request_msg +def test_delete_section_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. -def test_move_section_item_empty_call_grpc(): + unset_fields = transport.delete_section._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) + + +def test_delete_section_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.move_section_item), "__call__" - ) as call: - call.return_value = section.MoveSectionItemResponse() - client.move_section_item(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 = 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 + # get arguments that satisfy an http rule for this method + sample_request = {"name": "users/sample1/sections/sample2"} + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + ) + mock_args.update(sample_request) -def test_transport_kind_grpc_asyncio(): - transport = ChatServiceAsyncClient.get_transport_class("grpc_asyncio")( - credentials=async_anonymous_credentials() - ) - assert transport.kind == "grpc_asyncio" + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = "" + response_value._content = 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_section(**mock_args) -def test_initialize_client_w_grpc_asyncio(): - client = ChatServiceAsyncClient( - credentials=async_anonymous_credentials(), transport="grpc_asyncio" - ) - assert client is not None + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/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_create_message_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.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, - silent=True, - client_assigned_message_id="client_assigned_message_id_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.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", - ) +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", ) - 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 + # 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.update_section 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.update_section] = mock_rpc - # 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 + request = {} + client.update_section(request) + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -@pytest.mark.asyncio -async def test_get_membership_empty_call_grpc_asyncio(): - client = ChatServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) + client.update_section(request) - # 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 a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = membership.GetMembershipRequest() - 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_get_message_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_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, - silent=True, - client_assigned_message_id="client_assigned_message_id_value", - ) - ) - await client.get_message(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 = message.GetMessageRequest() - assert args[0] == request_msg + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).update_section._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + # verify required fields with default values are now present -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -@pytest.mark.asyncio -async def test_update_message_empty_call_grpc_asyncio(): - client = ChatServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", + 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) + + # 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.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, - silent=True, - client_assigned_message_id="client_assigned_message_id_value", - ) - ) - await client.update_message(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 = gc_message.UpdateMessageRequest() - assert args[0] == request_msg + 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) -# This test is a coverage 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", - ) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.delete_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) + response = client.update_section(request) - # 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 + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -@pytest.mark.asyncio -async def test_get_attachment_empty_call_grpc_asyncio(): - client = ChatServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", +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.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, + unset_fields = transport.update_section._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(("updateMask",)) + & set( + ( + "section", + "updateMask", ) ) - 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", +def test_update_section_rest_flattened(): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - # 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) + # Mock the http request call within the method and 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() - # 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 + # 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) -# This test is a coverage 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", - ) + # 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"} - # 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) + client.update_section(**mock_args) - # 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 + # Establish that the underlying call was 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] + ) -# This test is a coverage 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", +def test_update_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.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, - ) + # 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"]), ) - 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 +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", + ) -# This test is a coverage 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", - ) + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() - # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.get_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", - ) + # 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. ) - await client.get_space(request=None) + client._transport._wrapped_methods[client._transport.list_sections] = mock_rpc - # 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 + request = {} + client.list_sections(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_create_space_empty_call_grpc_asyncio(): - client = ChatServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) + client.list_sections(request) - # 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 a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = gc_space.CreateSpaceRequest() - assert args[0] == request_msg +def test_list_sections_rest_required_fields(request_type=section.ListSectionsRequest): + 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_set_up_space_empty_call_grpc_asyncio(): - client = ChatServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) ) - # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.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) + # 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_setup.SetUpSpaceRequest() - assert args[0] == request_msg + 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 -# This test is a coverage 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", - ) + jsonified_request["parent"] = "parent_value" - # 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", - ) + 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", ) - 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 + ) + 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_delete_space_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.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 + # 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 -# This test is a coverage 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", - ) + # Convert return value to protobuf type + return_value = section.ListSectionsResponse.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.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) + response_value._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 = space.CompleteImportSpaceRequest() - assert args[0] == request_msg + response = client.list_sections(request) + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -@pytest.mark.asyncio -async def test_find_direct_message_empty_call_grpc_asyncio(): - client = ChatServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", + +def test_list_sections_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.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", + unset_fields = transport.list_sections._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "pageSize", + "pageToken", ) ) - 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_find_group_chats_empty_call_grpc_asyncio(): - client = ChatServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", + & set(("parent",)) ) - # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.find_group_chats), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - space.FindGroupChatsResponse( - next_page_token="next_page_token_value", - ) - ) - await client.find_group_chats(request=None) - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = space.FindGroupChatsRequest() - assert args[0] == request_msg +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() -# This test is a coverage 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", - ) + # 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_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, - ) + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", ) - 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 + mock_args.update(sample_request) + # 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.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"} -# This test is a coverage 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.list_sections(**mock_args) - # 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, - ) + # Establish that the underlying call was 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] ) - 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", +def test_list_sections_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_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, - ) + # 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", ) - 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", +def test_list_sections_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_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", - ) + # 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(), + ], + 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(), + ], + ), ) - 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 - + # Two responses for two calls + response = response + response -# This test is a coverage 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", - ) + # 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 - # 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) + sample_request = {"parent": "users/sample1"} - # 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 + pager = client.list_sections(request=sample_request) + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, section.Section) for i in results) -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -@pytest.mark.asyncio -async def test_delete_reaction_empty_call_grpc_asyncio(): - client = ChatServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) + 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 - # 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 +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() -# This test is a coverage 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", - ) + # Ensure method has been cached + assert client._transport.position_section in client._transport._wrapped_methods - # 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", - ) + # Replace cached wrapped function with mock + mock_rpc = 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 ) - 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 + request = {} + client.position_section(request) + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -@pytest.mark.asyncio -async def test_get_custom_emoji_empty_call_grpc_asyncio(): - client = ChatServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) + client.position_section(request) - # 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 a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = reaction.GetCustomEmojiRequest() - assert args[0] == request_msg +def test_position_section_rest_required_fields( + request_type=section.PositionSectionRequest, +): + 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_custom_emojis_empty_call_grpc_asyncio(): - client = ChatServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) ) - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.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 + # 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) -# This test is a coverage 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", - ) + # verify required fields with default values are now present - # 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) + jsonified_request["name"] = "name_value" - # 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 + 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" -# This test is a coverage 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", + 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_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) + # 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, + } + 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_read_state.GetSpaceReadStateRequest() - assert args[0] == request_msg + 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) -# This test is a coverage 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", - ) + response_value._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_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) + response = client.position_section(request) - # 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 + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -@pytest.mark.asyncio -async def test_get_thread_read_state_empty_call_grpc_asyncio(): - client = ChatServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", +def test_position_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.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 - + unset_fields = transport.position_section._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. -@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", - ) +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", ) - 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 + # 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_space_events_empty_call_grpc_asyncio(): - client = ChatServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) + # Ensure method has been cached + assert ( + client._transport.list_section_items in client._transport._wrapped_methods + ) - # 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", - ) + # Replace cached wrapped function with mock + mock_rpc = 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 ) - 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 + request = {} + client.list_section_items(request) + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -@pytest.mark.asyncio -async def test_get_space_notification_setting_empty_call_grpc_asyncio(): - client = ChatServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) + client.list_section_items(request) - # 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 a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = space_notification_setting.GetSpaceNotificationSettingRequest() - assert args[0] == request_msg +def test_list_section_items_rest_required_fields( + request_type=section.ListSectionItemsRequest, +): + 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_update_space_notification_setting_empty_call_grpc_asyncio(): - client = ChatServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) ) - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.update_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) + # 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 = ( - gc_space_notification_setting.UpdateSpaceNotificationSettingRequest() - ) - assert args[0] == request_msg + 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 -# This test is a coverage 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", - ) + jsonified_request["parent"] = "parent_value" - # 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, - ) + 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", ) - 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 + ) + 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_delete_section_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.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) + # 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 - # 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 + 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) -# This test is a coverage 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", - ) + response_value._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_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) + response = client.list_section_items(request) - # 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 + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -@pytest.mark.asyncio -async def test_list_sections_empty_call_grpc_asyncio(): - client = ChatServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", +def test_list_section_items_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_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", + unset_fields = transport.list_section_items._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "filter", + "pageSize", + "pageToken", ) ) - 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", + & set(("parent",)) ) - # 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 +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() -# This test is a coverage 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", - ) + # get arguments that satisfy an http rule for this method + sample_request = {"parent": "users/sample1/sections/sample2"} - # 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", - ) + # get truthy value for each flattened field + mock_args = dict( + parent="parent_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 + mock_args.update(sample_request) + # 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"} -# This test is a coverage 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", - ) + client.list_section_items(**mock_args) - # 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() + # Establish that the underlying call was 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] ) - 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() +def test_list_section_items_rest_flattened_error(transport: str = "rest"): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, ) - assert transport.kind == "rest" + + # 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_create_message_rest_bad_request(request_type=gc_message.CreateMessageRequest): +def test_list_section_items_rest_pager(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 = 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), + # 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 sorted(expected_params) == sorted(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_find_group_chats_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_group_chats), "__call__") as call: + call.return_value = space.FindGroupChatsResponse() + client.find_group_chats(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = space.FindGroupChatsRequest() + assert args[0] == request_msg + + +# This 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_availability_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_availability), "__call__") as call: + call.return_value = availability.Availability() + client.get_availability(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = availability.GetAvailabilityRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_mark_as_active_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.mark_as_active), "__call__") as call: + call.return_value = availability.Availability() + client.mark_as_active(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = availability.MarkAsActiveRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_mark_as_away_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.mark_as_away), "__call__") as call: + call.return_value = availability.Availability() + client.mark_as_away(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = availability.MarkAsAwayRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_mark_as_do_not_disturb_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.mark_as_do_not_disturb), "__call__" + ) as call: + call.return_value = availability.Availability() + client.mark_as_do_not_disturb(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = availability.MarkAsDoNotDisturbRequest() + assert args[0] == request_msg + + +# This 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_availability_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_availability), "__call__" + ) as call: + call.return_value = gc_availability.Availability() + client.update_availability(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = gc_availability.UpdateAvailabilityRequest() + assert args[0] == request_msg + + +# This 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, + silent=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, + silent=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, + silent=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_find_group_chats_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_group_chats), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + space.FindGroupChatsResponse( + next_page_token="next_page_token_value", + ) + ) + await client.find_group_chats(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = space.FindGroupChatsRequest() + assert args[0] == request_msg + + +# This test is a coverage 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_availability_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_availability), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + availability.Availability( + name="name_value", + state=availability.Availability.State.ACTIVE, + ) + ) + await client.get_availability(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = availability.GetAvailabilityRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_mark_as_active_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.mark_as_active), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + availability.Availability( + name="name_value", + state=availability.Availability.State.ACTIVE, + ) + ) + await client.mark_as_active(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = availability.MarkAsActiveRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_mark_as_away_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.mark_as_away), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + availability.Availability( + name="name_value", + state=availability.Availability.State.ACTIVE, + ) + ) + await client.mark_as_away(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = availability.MarkAsAwayRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_mark_as_do_not_disturb_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.mark_as_do_not_disturb), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + availability.Availability( + name="name_value", + state=availability.Availability.State.ACTIVE, + ) + ) + await client.mark_as_do_not_disturb(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = availability.MarkAsDoNotDisturbRequest() + assert args[0] == request_msg + + +# This test is a coverage 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_availability_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_availability), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gc_availability.Availability( + name="name_value", + state=gc_availability.Availability.State.ACTIVE, + ) + ) + await client.update_availability(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = gc_availability.UpdateAvailabilityRequest() + assert args[0] == request_msg + + +# This test is a coverage 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() @@ -28667,74 +31085,320 @@ def get_message_fields(field): # 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 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, + silent=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.silent 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"), + ], + ) - if is_field_type_proto_plus_type: - message_fields = field.message.meta.fields.values() - # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types - else: # pragma: NO COVER - message_fields = field.message.DESCRIPTOR.fields - return message_fields + pre.assert_called_once() - runtime_nested_fields = [ - (field.name, nested_field.name) - for field in get_message_fields(test_field) - for nested_field in get_message_fields(field) - ] - subfields_not_in_runtime = [] +def test_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) - # 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 + # Mock the http request call within the method and fake a BadRequest 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) - 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] +@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 = gc_message.Message( + return_value = attachment.Attachment( name="name_value", - text="text_value", - formatted_text="formatted_text_value", - fallback_text="fallback_text_value", - argument_text="argument_text_value", - thread_reply=True, - silent=True, - client_assigned_message_id="client_assigned_message_id_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 @@ -28742,27 +31406,414 @@ 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 = 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.update_message(request) + response = client.get_attachment(request) # Establish that the response is the type that we expect. - assert isinstance(response, gc_message.Message) + assert isinstance(response, attachment.Attachment) 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.silent is True - assert response.client_assigned_message_id == "client_assigned_message_id_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" + + +@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) + + 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, + } + + req.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 + + 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 + + client.list_spaces( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + 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_update_message_rest_interceptors(null_interceptor): +def test_search_spaces_rest_interceptors(null_interceptor): transport = transports.ChatServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -28775,21 +31826,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_search_spaces" ) as post, mock.patch.object( - transports.ChatServiceRestInterceptor, "post_update_message_with_metadata" + transports.ChatServiceRestInterceptor, "post_search_spaces_with_metadata" ) as post_with_metadata, mock.patch.object( - transports.ChatServiceRestInterceptor, "pre_update_message" + transports.ChatServiceRestInterceptor, "pre_search_spaces" ) 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.SearchSpacesRequest.pb(space.SearchSpacesRequest()) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -28800,19 +31849,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.SearchSpacesResponse.to_json(space.SearchSpacesResponse()) req.return_value.content = return_value - request = gc_message.UpdateMessageRequest() + request = space.SearchSpacesRequest() 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.SearchSpacesResponse() + post_with_metadata.return_value = space.SearchSpacesResponse(), metadata - client.update_message( + client.search_spaces( request, metadata=[ ("key", "val"), @@ -28825,12 +31874,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_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/messages/sample2"} + request_init = {"name": "spaces/sample1"} request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -28846,45 +31895,79 @@ 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.get_space(request) @pytest.mark.parametrize( "request_type", [ - message.DeleteMessageRequest, + space.GetSpaceRequest, dict, ], ) -def test_delete_message_rest_call_success(request_type): +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/messages/sample2"} + 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 = None + 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, + ) # 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.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.get_space(request) # Establish that the response is the type that we expect. - assert response is None + 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" @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_delete_message_rest_interceptors(null_interceptor): +def test_get_space_rest_interceptors(null_interceptor): transport = transports.ChatServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -28897,11 +31980,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_get_space" + ) as post, + mock.patch.object( + transports.ChatServiceRestInterceptor, "post_get_space_with_metadata" + ) as post_with_metadata, + mock.patch.object( + transports.ChatServiceRestInterceptor, "pre_get_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 = space.GetSpaceRequest.pb(space.GetSpaceRequest()) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -28912,15 +32003,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 = space.Space.to_json(space.Space()) + req.return_value.content = return_value - request = message.DeleteMessageRequest() + request = space.GetSpaceRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata + post.return_value = space.Space() + post_with_metadata.return_value = space.Space(), metadata - client.delete_message( + client.get_space( request, metadata=[ ("key", "val"), @@ -28929,14 +32024,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_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/attachments/sample3"} + request_init = {} request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -28952,35 +32049,152 @@ 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.create_space(request) @pytest.mark.parametrize( "request_type", [ - attachment.GetAttachmentRequest, + gc_space.CreateSpaceRequest, dict, ], ) -def test_get_attachment_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/attachments/sample3"} + 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 = attachment.Attachment( + return_value = gc_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_=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 @@ -28988,25 +32202,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 = 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.get_attachment(request) + response = client.create_space(request) # Establish that the response is the type that we expect. - assert isinstance(response, attachment.Attachment) + assert isinstance(response, gc_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_ == 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_get_attachment_rest_interceptors(null_interceptor): +def test_create_space_rest_interceptors(null_interceptor): transport = transports.ChatServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -29019,21 +32243,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_create_space" ) as post, mock.patch.object( - transports.ChatServiceRestInterceptor, "post_get_attachment_with_metadata" + transports.ChatServiceRestInterceptor, "post_create_space_with_metadata" ) as post_with_metadata, mock.patch.object( - transports.ChatServiceRestInterceptor, "pre_get_attachment" + transports.ChatServiceRestInterceptor, "pre_create_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 = gc_space.CreateSpaceRequest.pb(gc_space.CreateSpaceRequest()) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -29044,19 +32266,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 = gc_space.Space.to_json(gc_space.Space()) req.return_value.content = return_value - request = attachment.GetAttachmentRequest() + request = gc_space.CreateSpaceRequest() 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 = gc_space.Space() + post_with_metadata.return_value = gc_space.Space(), metadata - client.get_attachment( + client.create_space( request, metadata=[ ("key", "val"), @@ -29069,14 +32291,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_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 = {"parent": "spaces/sample1"} + request_init = {} request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -29092,48 +32312,79 @@ 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.set_up_space(request) @pytest.mark.parametrize( "request_type", [ - attachment.UploadAttachmentRequest, + space_setup.SetUpSpaceRequest, dict, ], ) -def test_upload_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 = {"parent": "spaces/sample1"} + 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.UploadAttachmentResponse() + 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, + ) # 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) + 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.upload_attachment(request) + response = client.set_up_space(request) # Establish that the response is the type that we expect. - assert isinstance(response, attachment.UploadAttachmentResponse) + 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" @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_upload_attachment_rest_interceptors(null_interceptor): +def test_set_up_space_rest_interceptors(null_interceptor): transport = transports.ChatServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -29146,22 +32397,19 @@ def test_upload_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_upload_attachment" + transports.ChatServiceRestInterceptor, "post_set_up_space" ) as post, mock.patch.object( - transports.ChatServiceRestInterceptor, - "post_upload_attachment_with_metadata", + transports.ChatServiceRestInterceptor, "post_set_up_space_with_metadata" ) as post_with_metadata, mock.patch.object( - transports.ChatServiceRestInterceptor, "pre_upload_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.UploadAttachmentRequest.pb( - attachment.UploadAttachmentRequest() - ) + pb_message = space_setup.SetUpSpaceRequest.pb(space_setup.SetUpSpaceRequest()) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -29172,24 +32420,19 @@ def test_upload_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.UploadAttachmentResponse.to_json( - attachment.UploadAttachmentResponse() - ) + return_value = space.Space.to_json(space.Space()) req.return_value.content = return_value - request = attachment.UploadAttachmentRequest() + request = space_setup.SetUpSpaceRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = attachment.UploadAttachmentResponse() - post_with_metadata.return_value = ( - attachment.UploadAttachmentResponse(), - metadata, - ) + post.return_value = space.Space() + post_with_metadata.return_value = space.Space(), metadata - client.upload_attachment( + client.set_up_space( request, metadata=[ ("key", "val"), @@ -29202,12 +32445,12 @@ def test_upload_attachment_rest_interceptors(null_interceptor): post_with_metadata.assert_called_once() -def test_list_spaces_rest_bad_request(request_type=space.ListSpacesRequest): +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 = {} + request_init = {"space": {"name": "spaces/sample1"}} request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -29223,30 +32466,152 @@ def test_list_spaces_rest_bad_request(request_type=space.ListSpacesRequest): 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) + client.update_space(request) @pytest.mark.parametrize( "request_type", [ - space.ListSpacesRequest, + gc_space.UpdateSpaceRequest, dict, ], ) -def test_list_spaces_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 = {} + 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 + + # Determine if the message type is proto-plus or protobuf + test_field = gc_space.UpdateSpaceRequest.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 = 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 @@ -29254,20 +32619,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 @@ -29280,19 +32660,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", @@ -29303,19 +32683,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"), @@ -29328,12 +32708,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. @@ -29349,53 +32729,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 @@ -29408,19 +32780,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", @@ -29431,19 +32795,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"), @@ -29452,11 +32812,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" ) @@ -29477,17 +32837,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" ) @@ -29499,57 +32859,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 @@ -29562,19 +32891,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", @@ -29585,19 +32917,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"), @@ -29610,7 +32944,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" ) @@ -29631,152 +32967,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 @@ -29784,25 +33011,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 @@ -29812,7 +33039,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 @@ -29825,19 +33052,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", @@ -29848,19 +33076,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"), @@ -29873,7 +33101,7 @@ 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_find_group_chats_rest_bad_request(request_type=space.FindGroupChatsRequest): client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) @@ -29894,17 +33122,17 @@ 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.find_group_chats(request) @pytest.mark.parametrize( "request_type", [ - space_setup.SetUpSpaceRequest, + space.FindGroupChatsRequest, dict, ], ) -def test_set_up_space_rest_call_success(request_type): +def test_find_group_chats_rest_call_success(request_type): client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) @@ -29916,21 +33144,8 @@ def test_set_up_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.FindGroupChatsResponse( + next_page_token="next_page_token_value", ) # Wrap the value into a proper Response obj @@ -29938,35 +33153,20 @@ 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 = space.FindGroupChatsResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value.content = json_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.find_group_chats(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.FindGroupChatsPager) + assert response.next_page_token == "next_page_token_value" @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_set_up_space_rest_interceptors(null_interceptor): +def test_find_group_chats_rest_interceptors(null_interceptor): transport = transports.ChatServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -29979,19 +33179,19 @@ 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_find_group_chats" ) as post, mock.patch.object( - transports.ChatServiceRestInterceptor, "post_set_up_space_with_metadata" + transports.ChatServiceRestInterceptor, "post_find_group_chats_with_metadata" ) as post_with_metadata, mock.patch.object( - transports.ChatServiceRestInterceptor, "pre_set_up_space" + transports.ChatServiceRestInterceptor, "pre_find_group_chats" ) 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 = space.FindGroupChatsRequest.pb(space.FindGroupChatsRequest()) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -30002,19 +33202,21 @@ 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 = space.FindGroupChatsResponse.to_json( + space.FindGroupChatsResponse() + ) req.return_value.content = return_value - request = space_setup.SetUpSpaceRequest() + request = space.FindGroupChatsRequest() 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.FindGroupChatsResponse() + post_with_metadata.return_value = space.FindGroupChatsResponse(), metadata - client.set_up_space( + client.find_group_chats( request, metadata=[ ("key", "val"), @@ -30027,12 +33229,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_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 = {"space": {"name": "spaces/sample1"}} + request_init = {"parent": "spaces/sample1"} request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -30048,71 +33252,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.create_membership(request) @pytest.mark.parametrize( "request_type", [ - gc_space.UpdateSpaceRequest, + gc_membership.CreateMembershipRequest, dict, ], ) -def test_update_space_rest_call_success(request_type): +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 = {"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 = {"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, }, - "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.CreateMembershipRequest.meta.fields["membership"] def get_message_fields(field): # Given a field which is a message (composite type), return a list with @@ -30140,7 +33317,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 @@ -30170,30 +33347,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 @@ -30201,35 +33367,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.create_membership(request) - # Establish that the response is the type that we expect. - 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" + # 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 @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_update_space_rest_interceptors(null_interceptor): +def test_create_membership_rest_interceptors(null_interceptor): transport = transports.ChatServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -30242,19 +33395,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_create_membership" ) as post, mock.patch.object( - transports.ChatServiceRestInterceptor, "post_update_space_with_metadata" + transports.ChatServiceRestInterceptor, + "post_create_membership_with_metadata", ) as post_with_metadata, mock.patch.object( - transports.ChatServiceRestInterceptor, "pre_update_space" + transports.ChatServiceRestInterceptor, "pre_create_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.CreateMembershipRequest.pb( + gc_membership.CreateMembershipRequest() + ) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -30265,19 +33421,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.CreateMembershipRequest() 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.create_membership( request, metadata=[ ("key", "val"), @@ -30290,12 +33446,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_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 = {"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. @@ -30311,45 +33469,137 @@ 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.update_membership(request) @pytest.mark.parametrize( "request_type", [ - space.DeleteSpaceRequest, + gc_membership.UpdateMembershipRequest, dict, ], ) -def test_delete_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 = {"name": "spaces/sample1"} + 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": {}, + } + # 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"] + + 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 = request_type(**request_init) # Mock the http request call within the method and 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( + name="name_value", + state=gc_membership.Membership.MembershipState.JOINED, + role=gc_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 = 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_space(request) + response = client.update_membership(request) # Establish that the response is the type that we expect. - assert response is None + 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 @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_delete_space_rest_interceptors(null_interceptor): +def test_update_membership_rest_interceptors(null_interceptor): transport = transports.ChatServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -30362,11 +33612,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_update_membership" + ) as post, + mock.patch.object( + transports.ChatServiceRestInterceptor, + "post_update_membership_with_metadata", + ) as post_with_metadata, + mock.patch.object( + transports.ChatServiceRestInterceptor, "pre_update_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 = gc_membership.UpdateMembershipRequest.pb( + gc_membership.UpdateMembershipRequest() + ) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -30377,15 +33638,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 = gc_membership.Membership.to_json(gc_membership.Membership()) + req.return_value.content = return_value - request = space.DeleteSpaceRequest() + request = gc_membership.UpdateMembershipRequest() 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.delete_space( + client.update_membership( request, metadata=[ ("key", "val"), @@ -30394,16 +33659,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_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. @@ -30419,48 +33686,55 @@ 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.delete_membership(request) @pytest.mark.parametrize( "request_type", [ - space.CompleteImportSpaceRequest, + membership.DeleteMembershipRequest, dict, ], ) -def test_complete_import_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 = space.CompleteImportSpaceResponse() + 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 # Convert return value to protobuf type - return_value = space.CompleteImportSpaceResponse.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.complete_import_space(request) + response = client.delete_membership(request) # Establish that the response is the type that we expect. - assert isinstance(response, space.CompleteImportSpaceResponse) + 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_complete_import_space_rest_interceptors(null_interceptor): +def test_delete_membership_rest_interceptors(null_interceptor): transport = transports.ChatServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -30473,21 +33747,21 @@ 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_delete_membership" ) as post, mock.patch.object( transports.ChatServiceRestInterceptor, - "post_complete_import_space_with_metadata", + "post_delete_membership_with_metadata", ) as post_with_metadata, mock.patch.object( - transports.ChatServiceRestInterceptor, "pre_complete_import_space" + transports.ChatServiceRestInterceptor, "pre_delete_membership" ) 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 = membership.DeleteMembershipRequest.pb( + membership.DeleteMembershipRequest() ) transcode.return_value = { "method": "post", @@ -30499,21 +33773,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 = membership.Membership.to_json(membership.Membership()) req.return_value.content = return_value - request = space.CompleteImportSpaceRequest() + request = membership.DeleteMembershipRequest() 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 = membership.Membership() + post_with_metadata.return_value = membership.Membership(), metadata - client.complete_import_space( + client.delete_membership( request, metadata=[ ("key", "val"), @@ -30526,14 +33798,14 @@ 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_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 = {} + 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. @@ -30549,43 +33821,120 @@ 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.create_reaction(request) @pytest.mark.parametrize( "request_type", [ - space.FindDirectMessageRequest, + gc_reaction.CreateReactionRequest, dict, ], ) -def test_find_direct_message_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 = {} + 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.Space( + return_value = gc_reaction.Reaction( 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, ) # Wrap the value into a proper Response obj @@ -30593,35 +33942,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 = 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.find_direct_message(request) + response = client.create_reaction(request) # Establish that the response is the type that we expect. - assert isinstance(response, space.Space) + assert isinstance(response, gc_reaction.Reaction) 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" @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_find_direct_message_rest_interceptors(null_interceptor): +def test_create_reaction_rest_interceptors(null_interceptor): transport = transports.ChatServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -30634,20 +33968,21 @@ 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_create_reaction" ) as post, mock.patch.object( - transports.ChatServiceRestInterceptor, - "post_find_direct_message_with_metadata", + transports.ChatServiceRestInterceptor, "post_create_reaction_with_metadata" ) as post_with_metadata, mock.patch.object( - transports.ChatServiceRestInterceptor, "pre_find_direct_message" + transports.ChatServiceRestInterceptor, "pre_create_reaction" ) 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 = gc_reaction.CreateReactionRequest.pb( + gc_reaction.CreateReactionRequest() + ) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -30658,19 +33993,19 @@ 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 = gc_reaction.Reaction.to_json(gc_reaction.Reaction()) req.return_value.content = return_value - request = space.FindDirectMessageRequest() + request = gc_reaction.CreateReactionRequest() 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_reaction.Reaction() + post_with_metadata.return_value = gc_reaction.Reaction(), metadata - client.find_direct_message( + client.create_reaction( request, metadata=[ ("key", "val"), @@ -30683,12 +34018,12 @@ def test_find_direct_message_rest_interceptors(null_interceptor): post_with_metadata.assert_called_once() -def test_find_group_chats_rest_bad_request(request_type=space.FindGroupChatsRequest): +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. @@ -30704,29 +34039,29 @@ def test_find_group_chats_rest_bad_request(request_type=space.FindGroupChatsRequ response_value.request = mock.Mock() req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.find_group_chats(request) + client.list_reactions(request) @pytest.mark.parametrize( "request_type", [ - space.FindGroupChatsRequest, + reaction.ListReactionsRequest, dict, ], ) -def test_find_group_chats_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.FindGroupChatsResponse( + return_value = reaction.ListReactionsResponse( next_page_token="next_page_token_value", ) @@ -30735,20 +34070,20 @@ def test_find_group_chats_rest_call_success(request_type): response_value.status_code = 200 # Convert return value to protobuf type - return_value = space.FindGroupChatsResponse.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_group_chats(request) + response = client.list_reactions(request) # Establish that the response is the type that we expect. - assert isinstance(response, pagers.FindGroupChatsPager) + assert isinstance(response, pagers.ListReactionsPager) assert response.next_page_token == "next_page_token_value" @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_find_group_chats_rest_interceptors(null_interceptor): +def test_list_reactions_rest_interceptors(null_interceptor): transport = transports.ChatServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -30761,19 +34096,19 @@ def test_find_group_chats_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_group_chats" + transports.ChatServiceRestInterceptor, "post_list_reactions" ) as post, mock.patch.object( - transports.ChatServiceRestInterceptor, "post_find_group_chats_with_metadata" + transports.ChatServiceRestInterceptor, "post_list_reactions_with_metadata" ) as post_with_metadata, mock.patch.object( - transports.ChatServiceRestInterceptor, "pre_find_group_chats" + transports.ChatServiceRestInterceptor, "pre_list_reactions" ) as pre, ): pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = space.FindGroupChatsRequest.pb(space.FindGroupChatsRequest()) + pb_message = reaction.ListReactionsRequest.pb(reaction.ListReactionsRequest()) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -30784,21 +34119,21 @@ def test_find_group_chats_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.FindGroupChatsResponse.to_json( - space.FindGroupChatsResponse() + return_value = reaction.ListReactionsResponse.to_json( + reaction.ListReactionsResponse() ) req.return_value.content = return_value - request = space.FindGroupChatsRequest() + request = reaction.ListReactionsRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = space.FindGroupChatsResponse() - post_with_metadata.return_value = space.FindGroupChatsResponse(), metadata + post.return_value = reaction.ListReactionsResponse() + post_with_metadata.return_value = reaction.ListReactionsResponse(), metadata - client.find_group_chats( + client.list_reactions( request, metadata=[ ("key", "val"), @@ -30811,14 +34146,12 @@ def test_find_group_chats_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. @@ -30830,141 +34163,49 @@ def test_create_membership_rest_bad_request( 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_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 + 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_reaction(request) - if result and hasattr(result, "keys"): - for subfield in result.keys(): - if (field, subfield) not in runtime_nested_fields: - subfields_not_in_runtime.append( - { - "field": field, - "subfield": subfield, - "is_repeated": is_repeated, - } - ) - # Remove fields from the sample request which are not present in the runtime version of the dependency - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER - field = subfield_to_delete.get("field") - field_repeated = subfield_to_delete.get("is_repeated") - subfield = subfield_to_delete.get("subfield") - if subfield: - if field_repeated: - for i in range(0, len(request_init["membership"][field])): - del request_init["membership"][field][i][subfield] - else: - del request_init["membership"][field][subfield] +@pytest.mark.parametrize( + "request_type", + [ + reaction.DeleteReactionRequest, + dict, + ], +) +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 = {"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 @@ -30977,22 +34218,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", @@ -31003,19 +34233,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"), @@ -31024,18 +34250,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. @@ -31051,44 +34275,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 @@ -31116,7 +34332,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 @@ -31146,19 +34362,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 @@ -31166,22 +34383,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 @@ -31194,21 +34412,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", @@ -31220,19 +34438,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"), @@ -31245,14 +34463,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. @@ -31268,32 +34484,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 @@ -31301,22 +34518,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 @@ -31329,22 +34547,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", @@ -31355,19 +34570,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"), @@ -31380,14 +34595,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. @@ -31403,120 +34618,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 @@ -31524,20 +34649,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 @@ -31550,20 +34675,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", @@ -31575,19 +34701,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"), @@ -31600,12 +34728,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. @@ -31621,51 +34751,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 @@ -31678,19 +34802,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", @@ -31701,21 +34819,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"), @@ -31724,16 +34836,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. @@ -31749,45 +34861,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 @@ -31800,11 +34918,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", @@ -31815,15 +34944,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"), @@ -31832,16 +34967,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. @@ -31857,36 +34996,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 @@ -31914,7 +35054,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 @@ -31944,20 +35084,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 @@ -31965,23 +35102,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 @@ -31994,21 +35128,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", @@ -32020,19 +35154,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"), @@ -32045,12 +35181,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. @@ -32066,33 +35206,32 @@ 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 = reaction.CustomEmoji( + return_value = thread_read_state.ThreadReadState( 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 @@ -32100,23 +35239,20 @@ 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 = 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_custom_emoji(request) + response = client.get_thread_read_state(request) # Establish that the response is the type that we expect. - assert isinstance(response, reaction.CustomEmoji) + assert isinstance(response, thread_read_state.ThreadReadState) 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_get_custom_emoji_rest_interceptors(null_interceptor): +def test_get_thread_read_state_rest_interceptors(null_interceptor): transport = transports.ChatServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -32129,19 +35265,22 @@ 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_thread_read_state" ) as post, mock.patch.object( - transports.ChatServiceRestInterceptor, "post_get_custom_emoji_with_metadata" + transports.ChatServiceRestInterceptor, + "post_get_thread_read_state_with_metadata", ) as post_with_metadata, mock.patch.object( - transports.ChatServiceRestInterceptor, "pre_get_custom_emoji" + 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 = reaction.GetCustomEmojiRequest.pb(reaction.GetCustomEmojiRequest()) + pb_message = thread_read_state.GetThreadReadStateRequest.pb( + thread_read_state.GetThreadReadStateRequest() + ) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -32152,19 +35291,21 @@ 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 = thread_read_state.ThreadReadState.to_json( + thread_read_state.ThreadReadState() + ) req.return_value.content = return_value - request = reaction.GetCustomEmojiRequest() + request = thread_read_state.GetThreadReadStateRequest() 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 = thread_read_state.ThreadReadState() + post_with_metadata.return_value = thread_read_state.ThreadReadState(), metadata - client.get_custom_emoji( + client.get_thread_read_state( request, metadata=[ ("key", "val"), @@ -32177,14 +35318,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_get_availability_rest_bad_request( + request_type=availability.GetAvailabilityRequest, ): client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {} + request_init = {"name": "users/sample1/availability"} request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -32200,30 +35341,31 @@ 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.get_availability(request) @pytest.mark.parametrize( "request_type", [ - reaction.ListCustomEmojisRequest, + availability.GetAvailabilityRequest, dict, ], ) -def test_list_custom_emojis_rest_call_success(request_type): +def test_get_availability_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": "users/sample1/availability"} request = request_type(**request_init) # Mock the http request call within the method and 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( - next_page_token="next_page_token_value", + return_value = availability.Availability( + name="name_value", + state=availability.Availability.State.ACTIVE, ) # Wrap the value into a proper Response obj @@ -32231,20 +35373,21 @@ 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 = availability.Availability.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value.content = json_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.get_availability(request) # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListCustomEmojisPager) - assert response.next_page_token == "next_page_token_value" + assert isinstance(response, availability.Availability) + assert response.name == "name_value" + assert response.state == availability.Availability.State.ACTIVE @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_custom_emojis_rest_interceptors(null_interceptor): +def test_get_availability_rest_interceptors(null_interceptor): transport = transports.ChatServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -32257,21 +35400,20 @@ 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_get_availability" ) as post, mock.patch.object( - transports.ChatServiceRestInterceptor, - "post_list_custom_emojis_with_metadata", + transports.ChatServiceRestInterceptor, "post_get_availability_with_metadata" ) as post_with_metadata, mock.patch.object( - transports.ChatServiceRestInterceptor, "pre_list_custom_emojis" + transports.ChatServiceRestInterceptor, "pre_get_availability" ) 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 = availability.GetAvailabilityRequest.pb( + availability.GetAvailabilityRequest() ) transcode.return_value = { "method": "post", @@ -32283,21 +35425,19 @@ 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 = availability.Availability.to_json(availability.Availability()) req.return_value.content = return_value - request = reaction.ListCustomEmojisRequest() + request = availability.GetAvailabilityRequest() 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 = availability.Availability() + post_with_metadata.return_value = availability.Availability(), metadata - client.list_custom_emojis( + client.get_availability( request, metadata=[ ("key", "val"), @@ -32310,14 +35450,12 @@ 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_mark_as_active_rest_bad_request(request_type=availability.MarkAsActiveRequest): 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/availability"} request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -32333,45 +35471,53 @@ 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.mark_as_active(request) @pytest.mark.parametrize( "request_type", [ - reaction.DeleteCustomEmojiRequest, + availability.MarkAsActiveRequest, dict, ], ) -def test_delete_custom_emoji_rest_call_success(request_type): +def test_mark_as_active_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/availability"} request = request_type(**request_init) # Mock the http request call within the method and 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 = availability.Availability( + name="name_value", + state=availability.Availability.State.ACTIVE, + ) # 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 = availability.Availability.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) response_value.content = json_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.mark_as_active(request) # Establish that the response is the type that we expect. - assert response is None + assert isinstance(response, availability.Availability) + assert response.name == "name_value" + assert response.state == availability.Availability.State.ACTIVE @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_delete_custom_emoji_rest_interceptors(null_interceptor): +def test_mark_as_active_rest_interceptors(null_interceptor): transport = transports.ChatServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -32384,12 +35530,20 @@ 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_mark_as_active" + ) as post, + mock.patch.object( + transports.ChatServiceRestInterceptor, "post_mark_as_active_with_metadata" + ) as post_with_metadata, + mock.patch.object( + transports.ChatServiceRestInterceptor, "pre_mark_as_active" ) 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 = availability.MarkAsActiveRequest.pb( + availability.MarkAsActiveRequest() ) transcode.return_value = { "method": "post", @@ -32401,15 +35555,19 @@ 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 = availability.Availability.to_json(availability.Availability()) + req.return_value.content = return_value - request = reaction.DeleteCustomEmojiRequest() + request = availability.MarkAsActiveRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata + post.return_value = availability.Availability() + post_with_metadata.return_value = availability.Availability(), metadata - client.delete_custom_emoji( + client.mark_as_active( request, metadata=[ ("key", "val"), @@ -32418,16 +35576,146 @@ 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_mark_as_away_rest_bad_request(request_type=availability.MarkAsAwayRequest): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"name": "users/sample1/availability"} + 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.mark_as_away(request) + + +@pytest.mark.parametrize( + "request_type", + [ + availability.MarkAsAwayRequest, + dict, + ], +) +def test_mark_as_away_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/availability"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = availability.Availability( + name="name_value", + state=availability.Availability.State.ACTIVE, + ) + + # 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 = availability.Availability.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.mark_as_away(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, availability.Availability) + assert response.name == "name_value" + assert response.state == availability.Availability.State.ACTIVE + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_mark_as_away_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_mark_as_away" + ) as post, + mock.patch.object( + transports.ChatServiceRestInterceptor, "post_mark_as_away_with_metadata" + ) as post_with_metadata, + mock.patch.object( + transports.ChatServiceRestInterceptor, "pre_mark_as_away" + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = availability.MarkAsAwayRequest.pb(availability.MarkAsAwayRequest()) + 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 = availability.Availability.to_json(availability.Availability()) + req.return_value.content = return_value + + request = availability.MarkAsAwayRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = availability.Availability() + post_with_metadata.return_value = availability.Availability(), metadata + + client.mark_as_away( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_mark_as_do_not_disturb_rest_bad_request( + request_type=availability.MarkAsDoNotDisturbRequest, ): 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 = {"name": "users/sample1/availability"} request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -32443,30 +35731,31 @@ 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.mark_as_do_not_disturb(request) @pytest.mark.parametrize( "request_type", [ - space_read_state.GetSpaceReadStateRequest, + availability.MarkAsDoNotDisturbRequest, dict, ], ) -def test_get_space_read_state_rest_call_success(request_type): +def test_mark_as_do_not_disturb_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 = {"name": "users/sample1/availability"} request = request_type(**request_init) # Mock the http request call within the method and 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 = availability.Availability( name="name_value", + state=availability.Availability.State.ACTIVE, ) # Wrap the value into a proper Response obj @@ -32474,20 +35763,21 @@ 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 = availability.Availability.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value.content = json_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.mark_as_do_not_disturb(request) # Establish that the response is the type that we expect. - assert isinstance(response, space_read_state.SpaceReadState) + assert isinstance(response, availability.Availability) assert response.name == "name_value" + assert response.state == availability.Availability.State.ACTIVE @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_space_read_state_rest_interceptors(null_interceptor): +def test_mark_as_do_not_disturb_rest_interceptors(null_interceptor): transport = transports.ChatServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -32500,21 +35790,21 @@ 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_mark_as_do_not_disturb" ) as post, mock.patch.object( transports.ChatServiceRestInterceptor, - "post_get_space_read_state_with_metadata", + "post_mark_as_do_not_disturb_with_metadata", ) as post_with_metadata, mock.patch.object( - transports.ChatServiceRestInterceptor, "pre_get_space_read_state" + transports.ChatServiceRestInterceptor, "pre_mark_as_do_not_disturb" ) 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 = availability.MarkAsDoNotDisturbRequest.pb( + availability.MarkAsDoNotDisturbRequest() ) transcode.return_value = { "method": "post", @@ -32526,21 +35816,19 @@ 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 = availability.Availability.to_json(availability.Availability()) req.return_value.content = return_value - request = space_read_state.GetSpaceReadStateRequest() + request = availability.MarkAsDoNotDisturbRequest() 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 = availability.Availability() + post_with_metadata.return_value = availability.Availability(), metadata - client.get_space_read_state( + client.mark_as_do_not_disturb( request, metadata=[ ("key", "val"), @@ -32553,16 +35841,14 @@ 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_update_availability_rest_bad_request( + request_type=gc_availability.UpdateAvailabilityRequest, ): 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 = {"availability": {"name": "users/sample1/availability"}} request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -32578,37 +35864,52 @@ 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.update_availability(request) @pytest.mark.parametrize( "request_type", [ - gc_space_read_state.UpdateSpaceReadStateRequest, + gc_availability.UpdateAvailabilityRequest, dict, ], ) -def test_update_space_read_state_rest_call_success(request_type): +def test_update_availability_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 = {"availability": {"name": "users/sample1/availability"}} + request_init["availability"] = { + "name": "users/sample1/availability", + "state": 1, + "do_not_disturb_metadata": {"expiration_time": {"seconds": 751, "nanos": 543}}, + "custom_status": { + "text": "text_value", + "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", + }, + }, + }, + "expire_time": {}, + "ttl": {"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 = gc_space_read_state.UpdateSpaceReadStateRequest.meta.fields[ - "space_read_state" - ] + test_field = gc_availability.UpdateAvailabilityRequest.meta.fields["availability"] def get_message_fields(field): # Given a field which is a message (composite type), return a list with @@ -32636,7 +35937,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["availability"].items(): # pragma: NO COVER result = None is_repeated = False # For repeated fields @@ -32666,154 +35967,18 @@ 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["availability"][field])): + del request_init["availability"][field][i][subfield] else: - 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 = gc_space_read_state.SpaceReadState( - 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 = 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.update_space_read_state(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, gc_space_read_state.SpaceReadState) - assert response.name == "name_value" - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_update_space_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_update_space_read_state" - ) as post, - mock.patch.object( - transports.ChatServiceRestInterceptor, - "post_update_space_read_state_with_metadata", - ) as post_with_metadata, - mock.patch.object( - 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 = gc_space_read_state.UpdateSpaceReadStateRequest.pb( - gc_space_read_state.UpdateSpaceReadStateRequest() - ) - 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_space_read_state.SpaceReadState.to_json( - gc_space_read_state.SpaceReadState() - ) - req.return_value.content = return_value - - request = gc_space_read_state.UpdateSpaceReadStateRequest() - 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 - - client.update_space_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_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": "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. - 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) - - -@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" - ) - - # send a request that will satisfy transcoding - request_init = { - "name": "users/sample1/spaces/sample2/threads/sample3/threadReadState" - } + del request_init["availability"][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_availability.Availability( name="name_value", + state=gc_availability.Availability.State.ACTIVE, ) # Wrap the value into a proper Response obj @@ -32821,20 +35986,21 @@ 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_availability.Availability.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value.content = json_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_availability(request) # Establish that the response is the type that we expect. - assert isinstance(response, thread_read_state.ThreadReadState) + assert isinstance(response, gc_availability.Availability) assert response.name == "name_value" + assert response.state == gc_availability.Availability.State.ACTIVE @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_thread_read_state_rest_interceptors(null_interceptor): +def test_update_availability_rest_interceptors(null_interceptor): transport = transports.ChatServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -32847,21 +36013,21 @@ 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_availability" ) as post, mock.patch.object( transports.ChatServiceRestInterceptor, - "post_get_thread_read_state_with_metadata", + "post_update_availability_with_metadata", ) as post_with_metadata, mock.patch.object( - transports.ChatServiceRestInterceptor, "pre_get_thread_read_state" + transports.ChatServiceRestInterceptor, "pre_update_availability" ) 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_availability.UpdateAvailabilityRequest.pb( + gc_availability.UpdateAvailabilityRequest() ) transcode.return_value = { "method": "post", @@ -32873,21 +36039,21 @@ 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_availability.Availability.to_json( + gc_availability.Availability() ) req.return_value.content = return_value - request = thread_read_state.GetThreadReadStateRequest() + request = gc_availability.UpdateAvailabilityRequest() 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_availability.Availability() + post_with_metadata.return_value = gc_availability.Availability(), metadata - client.get_thread_read_state( + client.update_availability( request, metadata=[ ("key", "val"), @@ -35229,6 +38395,105 @@ def test_get_thread_read_state_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_availability_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.get_availability), "__call__") as call: + client.get_availability(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = availability.GetAvailabilityRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_mark_as_active_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.mark_as_active), "__call__") as call: + client.mark_as_active(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = availability.MarkAsActiveRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_mark_as_away_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.mark_as_away), "__call__") as call: + client.mark_as_away(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = availability.MarkAsAwayRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_mark_as_do_not_disturb_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.mark_as_do_not_disturb), "__call__" + ) as call: + client.mark_as_do_not_disturb(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = availability.MarkAsDoNotDisturbRequest() + assert args[0] == request_msg + + +# This 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_availability_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_availability), "__call__" + ) as call: + client.update_availability(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = gc_availability.UpdateAvailabilityRequest() + assert args[0] == request_msg + + # This 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_rest(): @@ -35515,6 +38780,11 @@ def test_chat_service_base_transport(): "get_space_read_state", "update_space_read_state", "get_thread_read_state", + "get_availability", + "mark_as_active", + "mark_as_away", + "mark_as_do_not_disturb", + "update_availability", "get_space_event", "list_space_events", "get_space_notification_setting", @@ -35592,6 +38862,8 @@ def test_chat_service_base_transport_with_credentials_file(): "https://www.googleapis.com/auth/chat.spaces", "https://www.googleapis.com/auth/chat.spaces.create", "https://www.googleapis.com/auth/chat.spaces.readonly", + "https://www.googleapis.com/auth/chat.users.availability", + "https://www.googleapis.com/auth/chat.users.availability.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", @@ -35653,6 +38925,8 @@ def test_chat_service_auth_adc(): "https://www.googleapis.com/auth/chat.spaces", "https://www.googleapis.com/auth/chat.spaces.create", "https://www.googleapis.com/auth/chat.spaces.readonly", + "https://www.googleapis.com/auth/chat.users.availability", + "https://www.googleapis.com/auth/chat.users.availability.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", @@ -35708,6 +38982,8 @@ def test_chat_service_transport_auth_adc(transport_class): "https://www.googleapis.com/auth/chat.spaces", "https://www.googleapis.com/auth/chat.spaces.create", "https://www.googleapis.com/auth/chat.spaces.readonly", + "https://www.googleapis.com/auth/chat.users.availability", + "https://www.googleapis.com/auth/chat.users.availability.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", @@ -35796,6 +39072,8 @@ def test_chat_service_transport_create_channel(transport_class, grpc_helpers): "https://www.googleapis.com/auth/chat.spaces", "https://www.googleapis.com/auth/chat.spaces.create", "https://www.googleapis.com/auth/chat.spaces.readonly", + "https://www.googleapis.com/auth/chat.users.availability", + "https://www.googleapis.com/auth/chat.users.availability.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", @@ -36022,6 +39300,21 @@ def test_chat_service_client_transport_session_collision(transport_name): session1 = client1.transport.get_thread_read_state._session session2 = client2.transport.get_thread_read_state._session assert session1 != session2 + session1 = client1.transport.get_availability._session + session2 = client2.transport.get_availability._session + assert session1 != session2 + session1 = client1.transport.mark_as_active._session + session2 = client2.transport.mark_as_active._session + assert session1 != session2 + session1 = client1.transport.mark_as_away._session + session2 = client2.transport.mark_as_away._session + assert session1 != session2 + session1 = client1.transport.mark_as_do_not_disturb._session + session2 = client2.transport.mark_as_do_not_disturb._session + assert session1 != session2 + session1 = client1.transport.update_availability._session + session2 = client2.transport.update_availability._session + assert session1 != session2 session1 = client1.transport.get_space_event._session session2 = client2.transport.get_space_event._session assert session1 != session2 @@ -36202,8 +39495,28 @@ def test_parse_attachment_path(): assert expected == actual +def test_availability_path(): + user = "cuttlefish" + expected = "users/{user}/availability".format( + user=user, + ) + actual = ChatServiceClient.availability_path(user) + assert expected == actual + + +def test_parse_availability_path(): + expected = { + "user": "mussel", + } + path = ChatServiceClient.availability_path(**expected) + + # Check that the path construction is reversible. + actual = ChatServiceClient.parse_availability_path(path) + assert expected == actual + + def test_custom_emoji_path(): - custom_emoji = "cuttlefish" + custom_emoji = "winkle" expected = "customEmojis/{custom_emoji}".format( custom_emoji=custom_emoji, ) @@ -36213,7 +39526,7 @@ def test_custom_emoji_path(): def test_parse_custom_emoji_path(): expected = { - "custom_emoji": "mussel", + "custom_emoji": "nautilus", } path = ChatServiceClient.custom_emoji_path(**expected) @@ -36223,8 +39536,8 @@ def test_parse_custom_emoji_path(): def test_membership_path(): - space = "winkle" - member = "nautilus" + space = "scallop" + member = "abalone" expected = "spaces/{space}/members/{member}".format( space=space, member=member, @@ -36235,8 +39548,8 @@ def test_membership_path(): def test_parse_membership_path(): expected = { - "space": "scallop", - "member": "abalone", + "space": "squid", + "member": "clam", } path = ChatServiceClient.membership_path(**expected) @@ -36246,8 +39559,8 @@ def test_parse_membership_path(): def test_message_path(): - space = "squid" - message = "clam" + space = "whelk" + message = "octopus" expected = "spaces/{space}/messages/{message}".format( space=space, message=message, @@ -36258,8 +39571,8 @@ def test_message_path(): def test_parse_message_path(): expected = { - "space": "whelk", - "message": "octopus", + "space": "oyster", + "message": "nudibranch", } path = ChatServiceClient.message_path(**expected) @@ -36269,9 +39582,9 @@ def test_parse_message_path(): def test_quoted_message_metadata_path(): - space = "oyster" - message = "nudibranch" - quoted_message_metadata = "cuttlefish" + space = "cuttlefish" + message = "mussel" + quoted_message_metadata = "winkle" expected = "spaces/{space}/messages/{message}/quotedMessageMetadata/{quoted_message_metadata}".format( space=space, message=message, @@ -36285,9 +39598,9 @@ def test_quoted_message_metadata_path(): def test_parse_quoted_message_metadata_path(): expected = { - "space": "mussel", - "message": "winkle", - "quoted_message_metadata": "nautilus", + "space": "nautilus", + "message": "scallop", + "quoted_message_metadata": "abalone", } path = ChatServiceClient.quoted_message_metadata_path(**expected) @@ -36297,9 +39610,9 @@ def test_parse_quoted_message_metadata_path(): def test_reaction_path(): - space = "scallop" - message = "abalone" - reaction = "squid" + space = "squid" + message = "clam" + reaction = "whelk" expected = "spaces/{space}/messages/{message}/reactions/{reaction}".format( space=space, message=message, @@ -36311,9 +39624,9 @@ def test_reaction_path(): def test_parse_reaction_path(): expected = { - "space": "clam", - "message": "whelk", - "reaction": "octopus", + "space": "octopus", + "message": "oyster", + "reaction": "nudibranch", } path = ChatServiceClient.reaction_path(**expected) @@ -36323,8 +39636,8 @@ def test_parse_reaction_path(): def test_section_path(): - user = "oyster" - section = "nudibranch" + user = "cuttlefish" + section = "mussel" expected = "users/{user}/sections/{section}".format( user=user, section=section, @@ -36335,8 +39648,8 @@ def test_section_path(): def test_parse_section_path(): expected = { - "user": "cuttlefish", - "section": "mussel", + "user": "winkle", + "section": "nautilus", } path = ChatServiceClient.section_path(**expected) @@ -36346,9 +39659,9 @@ def test_parse_section_path(): def test_section_item_path(): - user = "winkle" - section = "nautilus" - item = "scallop" + user = "scallop" + section = "abalone" + item = "squid" expected = "users/{user}/sections/{section}/items/{item}".format( user=user, section=section, @@ -36360,9 +39673,9 @@ def test_section_item_path(): def test_parse_section_item_path(): expected = { - "user": "abalone", - "section": "squid", - "item": "clam", + "user": "clam", + "section": "whelk", + "item": "octopus", } path = ChatServiceClient.section_item_path(**expected) @@ -36372,7 +39685,7 @@ def test_parse_section_item_path(): def test_space_path(): - space = "whelk" + space = "oyster" expected = "spaces/{space}".format( space=space, ) @@ -36382,7 +39695,7 @@ def test_space_path(): def test_parse_space_path(): expected = { - "space": "octopus", + "space": "nudibranch", } path = ChatServiceClient.space_path(**expected) @@ -36392,8 +39705,8 @@ def test_parse_space_path(): def test_space_event_path(): - space = "oyster" - space_event = "nudibranch" + space = "cuttlefish" + space_event = "mussel" expected = "spaces/{space}/spaceEvents/{space_event}".format( space=space, space_event=space_event, @@ -36404,8 +39717,8 @@ def test_space_event_path(): def test_parse_space_event_path(): expected = { - "space": "cuttlefish", - "space_event": "mussel", + "space": "winkle", + "space_event": "nautilus", } path = ChatServiceClient.space_event_path(**expected) @@ -36415,8 +39728,8 @@ def test_parse_space_event_path(): def test_space_notification_setting_path(): - user = "winkle" - space = "nautilus" + user = "scallop" + space = "abalone" expected = "users/{user}/spaces/{space}/spaceNotificationSetting".format( user=user, space=space, @@ -36427,8 +39740,8 @@ def test_space_notification_setting_path(): def test_parse_space_notification_setting_path(): expected = { - "user": "scallop", - "space": "abalone", + "user": "squid", + "space": "clam", } path = ChatServiceClient.space_notification_setting_path(**expected) @@ -36438,8 +39751,8 @@ def test_parse_space_notification_setting_path(): def test_space_read_state_path(): - user = "squid" - space = "clam" + user = "whelk" + space = "octopus" expected = "users/{user}/spaces/{space}/spaceReadState".format( user=user, space=space, @@ -36450,8 +39763,8 @@ def test_space_read_state_path(): def test_parse_space_read_state_path(): expected = { - "user": "whelk", - "space": "octopus", + "user": "oyster", + "space": "nudibranch", } path = ChatServiceClient.space_read_state_path(**expected) @@ -36461,8 +39774,8 @@ def test_parse_space_read_state_path(): def test_thread_path(): - space = "oyster" - thread = "nudibranch" + space = "cuttlefish" + thread = "mussel" expected = "spaces/{space}/threads/{thread}".format( space=space, thread=thread, @@ -36473,8 +39786,8 @@ def test_thread_path(): def test_parse_thread_path(): expected = { - "space": "cuttlefish", - "thread": "mussel", + "space": "winkle", + "thread": "nautilus", } path = ChatServiceClient.thread_path(**expected) @@ -36484,9 +39797,9 @@ def test_parse_thread_path(): def test_thread_read_state_path(): - user = "winkle" - space = "nautilus" - thread = "scallop" + user = "scallop" + space = "abalone" + thread = "squid" expected = "users/{user}/spaces/{space}/threads/{thread}/threadReadState".format( user=user, space=space, @@ -36498,9 +39811,9 @@ def test_thread_read_state_path(): def test_parse_thread_read_state_path(): expected = { - "user": "abalone", - "space": "squid", - "thread": "clam", + "user": "clam", + "space": "whelk", + "thread": "octopus", } path = ChatServiceClient.thread_read_state_path(**expected) @@ -36510,7 +39823,7 @@ def test_parse_thread_read_state_path(): def test_user_path(): - user = "whelk" + user = "oyster" expected = "users/{user}".format( user=user, ) @@ -36520,7 +39833,7 @@ def test_user_path(): def test_parse_user_path(): expected = { - "user": "octopus", + "user": "nudibranch", } path = ChatServiceClient.user_path(**expected) @@ -36530,7 +39843,7 @@ def test_parse_user_path(): def test_common_billing_account_path(): - billing_account = "oyster" + billing_account = "cuttlefish" expected = "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -36540,7 +39853,7 @@ def test_common_billing_account_path(): def test_parse_common_billing_account_path(): expected = { - "billing_account": "nudibranch", + "billing_account": "mussel", } path = ChatServiceClient.common_billing_account_path(**expected) @@ -36550,7 +39863,7 @@ def test_parse_common_billing_account_path(): def test_common_folder_path(): - folder = "cuttlefish" + folder = "winkle" expected = "folders/{folder}".format( folder=folder, ) @@ -36560,7 +39873,7 @@ def test_common_folder_path(): def test_parse_common_folder_path(): expected = { - "folder": "mussel", + "folder": "nautilus", } path = ChatServiceClient.common_folder_path(**expected) @@ -36570,7 +39883,7 @@ def test_parse_common_folder_path(): def test_common_organization_path(): - organization = "winkle" + organization = "scallop" expected = "organizations/{organization}".format( organization=organization, ) @@ -36580,7 +39893,7 @@ def test_common_organization_path(): def test_parse_common_organization_path(): expected = { - "organization": "nautilus", + "organization": "abalone", } path = ChatServiceClient.common_organization_path(**expected) @@ -36590,7 +39903,7 @@ def test_parse_common_organization_path(): def test_common_project_path(): - project = "scallop" + project = "squid" expected = "projects/{project}".format( project=project, ) @@ -36600,7 +39913,7 @@ def test_common_project_path(): def test_parse_common_project_path(): expected = { - "project": "abalone", + "project": "clam", } path = ChatServiceClient.common_project_path(**expected) @@ -36610,8 +39923,8 @@ def test_parse_common_project_path(): def test_common_location_path(): - project = "squid" - location = "clam" + project = "whelk" + location = "octopus" expected = "projects/{project}/locations/{location}".format( project=project, location=location, @@ -36622,8 +39935,8 @@ def test_common_location_path(): def test_parse_common_location_path(): expected = { - "project": "whelk", - "location": "octopus", + "project": "oyster", + "location": "nudibranch", } path = ChatServiceClient.common_location_path(**expected) diff --git a/packages/google-cloud-apigee-registry/.repo-metadata.json b/packages/google-cloud-apigee-registry/.repo-metadata.json index bfab488c479d..dd952078c000 100644 --- a/packages/google-cloud-apigee-registry/.repo-metadata.json +++ b/packages/google-cloud-apigee-registry/.repo-metadata.json @@ -1,14 +1,9 @@ { - "api_id": "apigeeregistry.googleapis.com", - "api_shortname": "apigeeregistry", - "client_documentation": "https://cloud.google.com/python/docs/reference/apigeeregistry/latest", - "default_version": "v1", + "client_documentation": "https://cloud.google.com/python/docs/reference/google-cloud-apigee-registry/latest", "distribution_name": "google-cloud-apigee-registry", "language": "python", "library_type": "GAPIC_AUTO", - "name": "apigeeregistry", - "name_pretty": "Apigee Registry", - "product_documentation": "https://cloud.google.com/apigee/", + "name": "google-cloud-apigee-registry", "release_level": "preview", "repo": "googleapis/google-cloud-python" } \ No newline at end of file diff --git a/packages/google-cloud-binary-authorization/google/cloud/binaryauthorization_v1beta1/services/binauthz_management_service_v1_beta1/async_client.py b/packages/google-cloud-binary-authorization/google/cloud/binaryauthorization_v1beta1/services/binauthz_management_service_v1_beta1/async_client.py index 28c5e990d380..e8e519bcd16a 100644 --- a/packages/google-cloud-binary-authorization/google/cloud/binaryauthorization_v1beta1/services/binauthz_management_service_v1_beta1/async_client.py +++ b/packages/google-cloud-binary-authorization/google/cloud/binaryauthorization_v1beta1/services/binauthz_management_service_v1_beta1/async_client.py @@ -45,6 +45,10 @@ OptionalRetry = Union[retries.AsyncRetry, object, None] # type: ignore import google.protobuf.timestamp_pb2 as timestamp_pb2 # type: ignore +from google.iam.v1 import ( + iam_policy_pb2, # type: ignore + policy_pb2, # type: ignore +) from google.cloud.binaryauthorization_v1beta1.services.binauthz_management_service_v1_beta1 import ( pagers, @@ -404,9 +408,8 @@ async def sample_get_policy(): Returns: google.cloud.binaryauthorization_v1beta1.types.Policy: - A - [policy][google.cloud.binaryauthorization.v1beta1.Policy] - for Binary Authorization. + A [policy][google.cloud.binaryauthorization.v1beta1.Policy] for Binary + Authorization. """ # Create or coerce a protobuf request object. @@ -531,9 +534,8 @@ async def sample_update_policy(): Returns: google.cloud.binaryauthorization_v1beta1.types.Policy: - A - [policy][google.cloud.binaryauthorization.v1beta1.Policy] - for Binary Authorization. + A [policy][google.cloud.binaryauthorization.v1beta1.Policy] for Binary + Authorization. """ # Create or coerce a protobuf request object. @@ -680,9 +682,9 @@ async def sample_create_attestor(): Returns: google.cloud.binaryauthorization_v1beta1.types.Attestor: - An [attestor][google.cloud.binaryauthorization.v1beta1.Attestor] that attests to container image - artifacts. An existing attestor cannot be modified - except where indicated. + An [attestor][google.cloud.binaryauthorization.v1beta1.Attestor] that attests + to container image artifacts. An existing attestor + cannot be modified except where indicated. """ # Create or coerce a protobuf request object. @@ -801,9 +803,9 @@ async def sample_get_attestor(): Returns: google.cloud.binaryauthorization_v1beta1.types.Attestor: - An [attestor][google.cloud.binaryauthorization.v1beta1.Attestor] that attests to container image - artifacts. An existing attestor cannot be modified - except where indicated. + An [attestor][google.cloud.binaryauthorization.v1beta1.Attestor] that attests + to container image artifacts. An existing attestor + cannot be modified except where indicated. """ # Create or coerce a protobuf request object. @@ -925,9 +927,9 @@ async def sample_update_attestor(): Returns: google.cloud.binaryauthorization_v1beta1.types.Attestor: - An [attestor][google.cloud.binaryauthorization.v1beta1.Attestor] that attests to container image - artifacts. An existing attestor cannot be modified - except where indicated. + An [attestor][google.cloud.binaryauthorization.v1beta1.Attestor] that attests + to container image artifacts. An existing attestor + cannot be modified except where indicated. """ # Create or coerce a protobuf request object. @@ -1215,6 +1217,329 @@ async def sample_delete_attestor(): metadata=metadata, ) + async def set_iam_policy( + self, + request: Optional[Union[iam_policy_pb2.SetIamPolicyRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> policy_pb2.Policy: + r"""Sets the IAM access control policy on the specified function. + + Replaces any existing policy. + + Args: + request (:class:`~.iam_policy_pb2.SetIamPolicyRequest`): + The request object. Request message for `SetIamPolicy` + method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.policy_pb2.Policy: + Defines an Identity and Access Management (IAM) policy. + It is used to specify access control policies for Cloud + Platform resources. + A ``Policy`` is a collection of ``bindings``. A + ``binding`` binds one or more ``members`` to a single + ``role``. Members can be user accounts, service + accounts, Google groups, and domains (such as G Suite). + A ``role`` is a named list of permissions (defined by + IAM or configured by users). A ``binding`` can + optionally specify a ``condition``, which is a logic + expression that further constrains the role binding + based on attributes about the request and/or target + resource. + + **JSON Example** + + :: + + { + "bindings": [ + { + "role": "roles/resourcemanager.organizationAdmin", + "members": [ + "user:mike@example.com", + "group:admins@example.com", + "domain:google.com", + "serviceAccount:my-project-id@appspot.gserviceaccount.com" + ] + }, + { + "role": "roles/resourcemanager.organizationViewer", + "members": ["user:eve@example.com"], + "condition": { + "title": "expirable access", + "description": "Does not grant access after Sep 2020", + "expression": "request.time < + timestamp('2020-10-01T00:00:00.000Z')", + } + } + ] + } + + **YAML Example** + + :: + + bindings: + - members: + - user:mike@example.com + - group:admins@example.com + - domain:google.com + - serviceAccount:my-project-id@appspot.gserviceaccount.com + role: roles/resourcemanager.organizationAdmin + - members: + - user:eve@example.com + role: roles/resourcemanager.organizationViewer + condition: + title: expirable access + description: Does not grant access after Sep 2020 + expression: request.time < timestamp('2020-10-01T00:00:00.000Z') + + For a description of IAM and its features, see the `IAM + developer's + guide `__. + """ + # Create or coerce a protobuf request object. + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if request is None: + request_pb = iam_policy_pb2.SetIamPolicyRequest() + elif isinstance(request, dict): + request_pb = iam_policy_pb2.SetIamPolicyRequest(**request) + else: + request_pb = request + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self.transport._wrapped_methods[self._client._transport.set_iam_policy] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("resource", request_pb.resource),) + ), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_iam_policy( + self, + request: Optional[Union[iam_policy_pb2.GetIamPolicyRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> policy_pb2.Policy: + r"""Gets the IAM access control policy for a function. + + Returns an empty policy if the function exists and does not have a + policy set. + + Args: + request (:class:`~.iam_policy_pb2.GetIamPolicyRequest`): + The request object. Request message for `GetIamPolicy` + method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if + any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.policy_pb2.Policy: + Defines an Identity and Access Management (IAM) policy. + It is used to specify access control policies for Cloud + Platform resources. + A ``Policy`` is a collection of ``bindings``. A + ``binding`` binds one or more ``members`` to a single + ``role``. Members can be user accounts, service + accounts, Google groups, and domains (such as G Suite). + A ``role`` is a named list of permissions (defined by + IAM or configured by users). A ``binding`` can + optionally specify a ``condition``, which is a logic + expression that further constrains the role binding + based on attributes about the request and/or target + resource. + + **JSON Example** + + :: + + { + "bindings": [ + { + "role": "roles/resourcemanager.organizationAdmin", + "members": [ + "user:mike@example.com", + "group:admins@example.com", + "domain:google.com", + "serviceAccount:my-project-id@appspot.gserviceaccount.com" + ] + }, + { + "role": "roles/resourcemanager.organizationViewer", + "members": ["user:eve@example.com"], + "condition": { + "title": "expirable access", + "description": "Does not grant access after Sep 2020", + "expression": "request.time < + timestamp('2020-10-01T00:00:00.000Z')", + } + } + ] + } + + **YAML Example** + + :: + + bindings: + - members: + - user:mike@example.com + - group:admins@example.com + - domain:google.com + - serviceAccount:my-project-id@appspot.gserviceaccount.com + role: roles/resourcemanager.organizationAdmin + - members: + - user:eve@example.com + role: roles/resourcemanager.organizationViewer + condition: + title: expirable access + description: Does not grant access after Sep 2020 + expression: request.time < timestamp('2020-10-01T00:00:00.000Z') + + For a description of IAM and its features, see the `IAM + developer's + guide `__. + """ + # Create or coerce a protobuf request object. + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if request is None: + request_pb = iam_policy_pb2.GetIamPolicyRequest() + elif isinstance(request, dict): + request_pb = iam_policy_pb2.GetIamPolicyRequest(**request) + else: + request_pb = request + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self.transport._wrapped_methods[self._client._transport.get_iam_policy] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("resource", request_pb.resource),) + ), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def test_iam_permissions( + self, + request: Optional[Union[iam_policy_pb2.TestIamPermissionsRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> iam_policy_pb2.TestIamPermissionsResponse: + r"""Tests the specified IAM permissions against the IAM access control + policy for a function. + + If the function does not exist, this will return an empty set + of permissions, not a NOT_FOUND error. + + Args: + request (:class:`~.iam_policy_pb2.TestIamPermissionsRequest`): + The request object. Request message for + `TestIamPermissions` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.iam_policy_pb2.TestIamPermissionsResponse: + Response message for ``TestIamPermissions`` method. + """ + # Create or coerce a protobuf request object. + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if request is None: + request_pb = iam_policy_pb2.TestIamPermissionsRequest() + elif isinstance(request, dict): + request_pb = iam_policy_pb2.TestIamPermissionsRequest(**request) + else: + request_pb = request + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self.transport._wrapped_methods[ + self._client._transport.test_iam_permissions + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("resource", request_pb.resource),) + ), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + async def __aenter__(self) -> "BinauthzManagementServiceV1Beta1AsyncClient": return self diff --git a/packages/google-cloud-binary-authorization/google/cloud/binaryauthorization_v1beta1/services/binauthz_management_service_v1_beta1/client.py b/packages/google-cloud-binary-authorization/google/cloud/binaryauthorization_v1beta1/services/binauthz_management_service_v1_beta1/client.py index 754e329e30c3..20a8c23522d4 100644 --- a/packages/google-cloud-binary-authorization/google/cloud/binaryauthorization_v1beta1/services/binauthz_management_service_v1_beta1/client.py +++ b/packages/google-cloud-binary-authorization/google/cloud/binaryauthorization_v1beta1/services/binauthz_management_service_v1_beta1/client.py @@ -62,6 +62,10 @@ _LOGGER = std_logging.getLogger(__name__) import google.protobuf.timestamp_pb2 as timestamp_pb2 # type: ignore +from google.iam.v1 import ( + iam_policy_pb2, # type: ignore + policy_pb2, # type: ignore +) from google.cloud.binaryauthorization_v1beta1.services.binauthz_management_service_v1_beta1 import ( pagers, @@ -845,9 +849,8 @@ def sample_get_policy(): Returns: google.cloud.binaryauthorization_v1beta1.types.Policy: - A - [policy][google.cloud.binaryauthorization.v1beta1.Policy] - for Binary Authorization. + A [policy][google.cloud.binaryauthorization.v1beta1.Policy] for Binary + Authorization. """ # Create or coerce a protobuf request object. @@ -969,9 +972,8 @@ def sample_update_policy(): Returns: google.cloud.binaryauthorization_v1beta1.types.Policy: - A - [policy][google.cloud.binaryauthorization.v1beta1.Policy] - for Binary Authorization. + A [policy][google.cloud.binaryauthorization.v1beta1.Policy] for Binary + Authorization. """ # Create or coerce a protobuf request object. @@ -1115,9 +1117,9 @@ def sample_create_attestor(): Returns: google.cloud.binaryauthorization_v1beta1.types.Attestor: - An [attestor][google.cloud.binaryauthorization.v1beta1.Attestor] that attests to container image - artifacts. An existing attestor cannot be modified - except where indicated. + An [attestor][google.cloud.binaryauthorization.v1beta1.Attestor] that attests + to container image artifacts. An existing attestor + cannot be modified except where indicated. """ # Create or coerce a protobuf request object. @@ -1233,9 +1235,9 @@ def sample_get_attestor(): Returns: google.cloud.binaryauthorization_v1beta1.types.Attestor: - An [attestor][google.cloud.binaryauthorization.v1beta1.Attestor] that attests to container image - artifacts. An existing attestor cannot be modified - except where indicated. + An [attestor][google.cloud.binaryauthorization.v1beta1.Attestor] that attests + to container image artifacts. An existing attestor + cannot be modified except where indicated. """ # Create or coerce a protobuf request object. @@ -1354,9 +1356,9 @@ def sample_update_attestor(): Returns: google.cloud.binaryauthorization_v1beta1.types.Attestor: - An [attestor][google.cloud.binaryauthorization.v1beta1.Attestor] that attests to container image - artifacts. An existing attestor cannot be modified - except where indicated. + An [attestor][google.cloud.binaryauthorization.v1beta1.Attestor] that attests + to container image artifacts. An existing attestor + cannot be modified except where indicated. """ # Create or coerce a protobuf request object. @@ -1648,6 +1650,339 @@ def __exit__(self, type, value, traceback): """ self.transport.close() + def set_iam_policy( + self, + request: Optional[Union[iam_policy_pb2.SetIamPolicyRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> policy_pb2.Policy: + r"""Sets the IAM access control policy on the specified function. + + Replaces any existing policy. + + Args: + request (:class:`~.iam_policy_pb2.SetIamPolicyRequest`): + The request object. Request message for `SetIamPolicy` + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.policy_pb2.Policy: + Defines an Identity and Access Management (IAM) policy. + It is used to specify access control policies for Cloud + Platform resources. + A ``Policy`` is a collection of ``bindings``. A + ``binding`` binds one or more ``members`` to a single + ``role``. Members can be user accounts, service + accounts, Google groups, and domains (such as G Suite). + A ``role`` is a named list of permissions (defined by + IAM or configured by users). A ``binding`` can + optionally specify a ``condition``, which is a logic + expression that further constrains the role binding + based on attributes about the request and/or target + resource. + + **JSON Example** + + :: + + { + "bindings": [ + { + "role": "roles/resourcemanager.organizationAdmin", + "members": [ + "user:mike@example.com", + "group:admins@example.com", + "domain:google.com", + "serviceAccount:my-project-id@appspot.gserviceaccount.com" + ] + }, + { + "role": "roles/resourcemanager.organizationViewer", + "members": ["user:eve@example.com"], + "condition": { + "title": "expirable access", + "description": "Does not grant access after Sep 2020", + "expression": "request.time < + timestamp('2020-10-01T00:00:00.000Z')", + } + } + ] + } + + **YAML Example** + + :: + + bindings: + - members: + - user:mike@example.com + - group:admins@example.com + - domain:google.com + - serviceAccount:my-project-id@appspot.gserviceaccount.com + role: roles/resourcemanager.organizationAdmin + - members: + - user:eve@example.com + role: roles/resourcemanager.organizationViewer + condition: + title: expirable access + description: Does not grant access after Sep 2020 + expression: request.time < timestamp('2020-10-01T00:00:00.000Z') + + For a description of IAM and its features, see the `IAM + developer's + guide `__. + """ + # Create or coerce a protobuf request object. + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if request is None: + request_pb = iam_policy_pb2.SetIamPolicyRequest() + elif isinstance(request, dict): + request_pb = iam_policy_pb2.SetIamPolicyRequest(**request) + else: + request_pb = request + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.set_iam_policy] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("resource", request_pb.resource),) + ), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + try: + # Send the request. + response = rpc( + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + except core_exceptions.GoogleAPICallError as e: + self._add_cred_info_for_auth_errors(e) + raise e + + def get_iam_policy( + self, + request: Optional[Union[iam_policy_pb2.GetIamPolicyRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> policy_pb2.Policy: + r"""Gets the IAM access control policy for a function. + + Returns an empty policy if the function exists and does not have a + policy set. + + Args: + request (:class:`~.iam_policy_pb2.GetIamPolicyRequest`): + The request object. Request message for `GetIamPolicy` + method. + retry (google.api_core.retry.Retry): Designation of what errors, if + any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.policy_pb2.Policy: + Defines an Identity and Access Management (IAM) policy. + It is used to specify access control policies for Cloud + Platform resources. + A ``Policy`` is a collection of ``bindings``. A + ``binding`` binds one or more ``members`` to a single + ``role``. Members can be user accounts, service + accounts, Google groups, and domains (such as G Suite). + A ``role`` is a named list of permissions (defined by + IAM or configured by users). A ``binding`` can + optionally specify a ``condition``, which is a logic + expression that further constrains the role binding + based on attributes about the request and/or target + resource. + + **JSON Example** + + :: + + { + "bindings": [ + { + "role": "roles/resourcemanager.organizationAdmin", + "members": [ + "user:mike@example.com", + "group:admins@example.com", + "domain:google.com", + "serviceAccount:my-project-id@appspot.gserviceaccount.com" + ] + }, + { + "role": "roles/resourcemanager.organizationViewer", + "members": ["user:eve@example.com"], + "condition": { + "title": "expirable access", + "description": "Does not grant access after Sep 2020", + "expression": "request.time < + timestamp('2020-10-01T00:00:00.000Z')", + } + } + ] + } + + **YAML Example** + + :: + + bindings: + - members: + - user:mike@example.com + - group:admins@example.com + - domain:google.com + - serviceAccount:my-project-id@appspot.gserviceaccount.com + role: roles/resourcemanager.organizationAdmin + - members: + - user:eve@example.com + role: roles/resourcemanager.organizationViewer + condition: + title: expirable access + description: Does not grant access after Sep 2020 + expression: request.time < timestamp('2020-10-01T00:00:00.000Z') + + For a description of IAM and its features, see the `IAM + developer's + guide `__. + """ + # Create or coerce a protobuf request object. + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if request is None: + request_pb = iam_policy_pb2.GetIamPolicyRequest() + elif isinstance(request, dict): + request_pb = iam_policy_pb2.GetIamPolicyRequest(**request) + else: + request_pb = request + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_iam_policy] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("resource", request_pb.resource),) + ), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + try: + # Send the request. + response = rpc( + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + except core_exceptions.GoogleAPICallError as e: + self._add_cred_info_for_auth_errors(e) + raise e + + def test_iam_permissions( + self, + request: Optional[Union[iam_policy_pb2.TestIamPermissionsRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> iam_policy_pb2.TestIamPermissionsResponse: + r"""Tests the specified IAM permissions against the IAM access control + policy for a function. + + If the function does not exist, this will return an empty set + of permissions, not a NOT_FOUND error. + + Args: + request (:class:`~.iam_policy_pb2.TestIamPermissionsRequest`): + The request object. Request message for + `TestIamPermissions` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.iam_policy_pb2.TestIamPermissionsResponse: + Response message for ``TestIamPermissions`` method. + """ + # Create or coerce a protobuf request object. + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if request is None: + request_pb = iam_policy_pb2.TestIamPermissionsRequest() + elif isinstance(request, dict): + request_pb = iam_policy_pb2.TestIamPermissionsRequest(**request) + else: + request_pb = request + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.test_iam_permissions] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("resource", request_pb.resource),) + ), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + try: + # Send the request. + response = rpc( + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + except core_exceptions.GoogleAPICallError as e: + self._add_cred_info_for_auth_errors(e) + raise e + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( gapic_version=package_version.__version__ diff --git a/packages/google-cloud-binary-authorization/google/cloud/binaryauthorization_v1beta1/services/binauthz_management_service_v1_beta1/transports/base.py b/packages/google-cloud-binary-authorization/google/cloud/binaryauthorization_v1beta1/services/binauthz_management_service_v1_beta1/transports/base.py index ce79824ce257..8f9f00ef9abf 100644 --- a/packages/google-cloud-binary-authorization/google/cloud/binaryauthorization_v1beta1/services/binauthz_management_service_v1_beta1/transports/base.py +++ b/packages/google-cloud-binary-authorization/google/cloud/binaryauthorization_v1beta1/services/binauthz_management_service_v1_beta1/transports/base.py @@ -24,6 +24,10 @@ from google.api_core import gapic_v1 from google.api_core import retry as retries from google.auth import credentials as ga_credentials # type: ignore +from google.iam.v1 import ( + iam_policy_pb2, # type: ignore + policy_pb2, # type: ignore +) from google.oauth2 import service_account # type: ignore from google.cloud.binaryauthorization_v1beta1 import gapic_version as package_version @@ -238,6 +242,21 @@ def _prep_wrapped_messages(self, client_info): default_timeout=600.0, client_info=client_info, ), + self.get_iam_policy: gapic_v1.method.wrap_method( + self.get_iam_policy, + default_timeout=None, + client_info=client_info, + ), + self.set_iam_policy: gapic_v1.method.wrap_method( + self.set_iam_policy, + default_timeout=None, + client_info=client_info, + ), + self.test_iam_permissions: gapic_v1.method.wrap_method( + self.test_iam_permissions, + default_timeout=None, + client_info=client_info, + ), } def close(self): @@ -311,6 +330,36 @@ def delete_attestor( ]: raise NotImplementedError() + @property + def set_iam_policy( + self, + ) -> Callable[ + [iam_policy_pb2.SetIamPolicyRequest], + Union[policy_pb2.Policy, Awaitable[policy_pb2.Policy]], + ]: + raise NotImplementedError() + + @property + def get_iam_policy( + self, + ) -> Callable[ + [iam_policy_pb2.GetIamPolicyRequest], + Union[policy_pb2.Policy, Awaitable[policy_pb2.Policy]], + ]: + raise NotImplementedError() + + @property + def test_iam_permissions( + self, + ) -> Callable[ + [iam_policy_pb2.TestIamPermissionsRequest], + Union[ + iam_policy_pb2.TestIamPermissionsResponse, + Awaitable[iam_policy_pb2.TestIamPermissionsResponse], + ], + ]: + raise NotImplementedError() + @property def kind(self) -> str: raise NotImplementedError() diff --git a/packages/google-cloud-binary-authorization/google/cloud/binaryauthorization_v1beta1/services/binauthz_management_service_v1_beta1/transports/grpc.py b/packages/google-cloud-binary-authorization/google/cloud/binaryauthorization_v1beta1/services/binauthz_management_service_v1_beta1/transports/grpc.py index 5e9a3da77cee..3047a0c310b2 100644 --- a/packages/google-cloud-binary-authorization/google/cloud/binaryauthorization_v1beta1/services/binauthz_management_service_v1_beta1/transports/grpc.py +++ b/packages/google-cloud-binary-authorization/google/cloud/binaryauthorization_v1beta1/services/binauthz_management_service_v1_beta1/transports/grpc.py @@ -27,6 +27,10 @@ from google.api_core import gapic_v1, grpc_helpers from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore +from google.iam.v1 import ( + iam_policy_pb2, # type: ignore + policy_pb2, # type: ignore +) from google.protobuf.json_format import MessageToJson from google.cloud.binaryauthorization_v1beta1.types import resources, service @@ -558,6 +562,86 @@ def delete_attestor( def close(self): self._logged_channel.close() + @property + def set_iam_policy( + self, + ) -> Callable[[iam_policy_pb2.SetIamPolicyRequest], policy_pb2.Policy]: + r"""Return a callable for the set iam policy method over gRPC. + Sets the IAM access control policy on the specified + function. Replaces any existing policy. + Returns: + Callable[[~.SetIamPolicyRequest], + ~.Policy]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "set_iam_policy" not in self._stubs: + self._stubs["set_iam_policy"] = self._logged_channel.unary_unary( + "/google.iam.v1.IAMPolicy/SetIamPolicy", + request_serializer=iam_policy_pb2.SetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs["set_iam_policy"] + + @property + def get_iam_policy( + self, + ) -> Callable[[iam_policy_pb2.GetIamPolicyRequest], policy_pb2.Policy]: + r"""Return a callable for the get iam policy method over gRPC. + Gets the IAM access control policy for a function. + Returns an empty policy if the function exists and does + not have a policy set. + Returns: + Callable[[~.GetIamPolicyRequest], + ~.Policy]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_iam_policy" not in self._stubs: + self._stubs["get_iam_policy"] = self._logged_channel.unary_unary( + "/google.iam.v1.IAMPolicy/GetIamPolicy", + request_serializer=iam_policy_pb2.GetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs["get_iam_policy"] + + @property + def test_iam_permissions( + self, + ) -> Callable[ + [iam_policy_pb2.TestIamPermissionsRequest], + iam_policy_pb2.TestIamPermissionsResponse, + ]: + r"""Return a callable for the test iam permissions method over gRPC. + Tests the specified permissions against the IAM access control + policy for a function. If the function does not exist, this will + return an empty set of permissions, not a NOT_FOUND error. + Returns: + Callable[[~.TestIamPermissionsRequest], + ~.TestIamPermissionsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "test_iam_permissions" not in self._stubs: + self._stubs["test_iam_permissions"] = self._logged_channel.unary_unary( + "/google.iam.v1.IAMPolicy/TestIamPermissions", + request_serializer=iam_policy_pb2.TestIamPermissionsRequest.SerializeToString, + response_deserializer=iam_policy_pb2.TestIamPermissionsResponse.FromString, + ) + return self._stubs["test_iam_permissions"] + @property def kind(self) -> str: return "grpc" diff --git a/packages/google-cloud-binary-authorization/google/cloud/binaryauthorization_v1beta1/services/binauthz_management_service_v1_beta1/transports/grpc_asyncio.py b/packages/google-cloud-binary-authorization/google/cloud/binaryauthorization_v1beta1/services/binauthz_management_service_v1_beta1/transports/grpc_asyncio.py index a00fa055941b..30a7c0bf3392 100644 --- a/packages/google-cloud-binary-authorization/google/cloud/binaryauthorization_v1beta1/services/binauthz_management_service_v1_beta1/transports/grpc_asyncio.py +++ b/packages/google-cloud-binary-authorization/google/cloud/binaryauthorization_v1beta1/services/binauthz_management_service_v1_beta1/transports/grpc_asyncio.py @@ -29,6 +29,10 @@ from google.api_core import retry_async as retries from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore +from google.iam.v1 import ( + iam_policy_pb2, # type: ignore + policy_pb2, # type: ignore +) from google.protobuf.json_format import MessageToJson from grpc.experimental import aio # type: ignore @@ -665,6 +669,21 @@ def _prep_wrapped_messages(self, client_info): default_timeout=600.0, client_info=client_info, ), + self.get_iam_policy: self._wrap_method( + self.get_iam_policy, + default_timeout=None, + client_info=client_info, + ), + self.set_iam_policy: self._wrap_method( + self.set_iam_policy, + default_timeout=None, + client_info=client_info, + ), + self.test_iam_permissions: self._wrap_method( + self.test_iam_permissions, + default_timeout=None, + client_info=client_info, + ), } def _wrap_method(self, func, *args, **kwargs): @@ -679,5 +698,85 @@ def close(self): def kind(self) -> str: return "grpc_asyncio" + @property + def set_iam_policy( + self, + ) -> Callable[[iam_policy_pb2.SetIamPolicyRequest], policy_pb2.Policy]: + r"""Return a callable for the set iam policy method over gRPC. + Sets the IAM access control policy on the specified + function. Replaces any existing policy. + Returns: + Callable[[~.SetIamPolicyRequest], + ~.Policy]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "set_iam_policy" not in self._stubs: + self._stubs["set_iam_policy"] = self._logged_channel.unary_unary( + "/google.iam.v1.IAMPolicy/SetIamPolicy", + request_serializer=iam_policy_pb2.SetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs["set_iam_policy"] + + @property + def get_iam_policy( + self, + ) -> Callable[[iam_policy_pb2.GetIamPolicyRequest], policy_pb2.Policy]: + r"""Return a callable for the get iam policy method over gRPC. + Gets the IAM access control policy for a function. + Returns an empty policy if the function exists and does + not have a policy set. + Returns: + Callable[[~.GetIamPolicyRequest], + ~.Policy]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_iam_policy" not in self._stubs: + self._stubs["get_iam_policy"] = self._logged_channel.unary_unary( + "/google.iam.v1.IAMPolicy/GetIamPolicy", + request_serializer=iam_policy_pb2.GetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs["get_iam_policy"] + + @property + def test_iam_permissions( + self, + ) -> Callable[ + [iam_policy_pb2.TestIamPermissionsRequest], + iam_policy_pb2.TestIamPermissionsResponse, + ]: + r"""Return a callable for the test iam permissions method over gRPC. + Tests the specified permissions against the IAM access control + policy for a function. If the function does not exist, this will + return an empty set of permissions, not a NOT_FOUND error. + Returns: + Callable[[~.TestIamPermissionsRequest], + ~.TestIamPermissionsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "test_iam_permissions" not in self._stubs: + self._stubs["test_iam_permissions"] = self._logged_channel.unary_unary( + "/google.iam.v1.IAMPolicy/TestIamPermissions", + request_serializer=iam_policy_pb2.TestIamPermissionsRequest.SerializeToString, + response_deserializer=iam_policy_pb2.TestIamPermissionsResponse.FromString, + ) + return self._stubs["test_iam_permissions"] + __all__ = ("BinauthzManagementServiceV1Beta1GrpcAsyncIOTransport",) diff --git a/packages/google-cloud-binary-authorization/google/cloud/binaryauthorization_v1beta1/services/binauthz_management_service_v1_beta1/transports/rest.py b/packages/google-cloud-binary-authorization/google/cloud/binaryauthorization_v1beta1/services/binauthz_management_service_v1_beta1/transports/rest.py index 865f042b4c4a..0bff41979f42 100644 --- a/packages/google-cloud-binary-authorization/google/cloud/binaryauthorization_v1beta1/services/binauthz_management_service_v1_beta1/transports/rest.py +++ b/packages/google-cloud-binary-authorization/google/cloud/binaryauthorization_v1beta1/services/binauthz_management_service_v1_beta1/transports/rest.py @@ -26,6 +26,10 @@ from google.api_core import retry as retries from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.requests import AuthorizedSession # type: ignore +from google.iam.v1 import ( + iam_policy_pb2, # type: ignore + policy_pb2, # type: ignore +) from google.protobuf import json_format from requests import __version__ as requests_version @@ -409,6 +413,78 @@ def post_update_policy_with_metadata( """ return response, metadata + def pre_get_iam_policy( + self, + request: iam_policy_pb2.GetIamPolicyRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + iam_policy_pb2.GetIamPolicyRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for get_iam_policy + + Override in a subclass to manipulate the request or metadata + before they are sent to the BinauthzManagementServiceV1Beta1 server. + """ + return request, metadata + + def post_get_iam_policy(self, response: policy_pb2.Policy) -> policy_pb2.Policy: + """Post-rpc interceptor for get_iam_policy + + Override in a subclass to manipulate the response + after it is returned by the BinauthzManagementServiceV1Beta1 server but before + it is returned to user code. + """ + return response + + def pre_set_iam_policy( + self, + request: iam_policy_pb2.SetIamPolicyRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + iam_policy_pb2.SetIamPolicyRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for set_iam_policy + + Override in a subclass to manipulate the request or metadata + before they are sent to the BinauthzManagementServiceV1Beta1 server. + """ + return request, metadata + + def post_set_iam_policy(self, response: policy_pb2.Policy) -> policy_pb2.Policy: + """Post-rpc interceptor for set_iam_policy + + Override in a subclass to manipulate the response + after it is returned by the BinauthzManagementServiceV1Beta1 server but before + it is returned to user code. + """ + return response + + def pre_test_iam_permissions( + self, + request: iam_policy_pb2.TestIamPermissionsRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + iam_policy_pb2.TestIamPermissionsRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for test_iam_permissions + + Override in a subclass to manipulate the request or metadata + before they are sent to the BinauthzManagementServiceV1Beta1 server. + """ + return request, metadata + + def post_test_iam_permissions( + self, response: iam_policy_pb2.TestIamPermissionsResponse + ) -> iam_policy_pb2.TestIamPermissionsResponse: + """Post-rpc interceptor for test_iam_permissions + + Override in a subclass to manipulate the response + after it is returned by the BinauthzManagementServiceV1Beta1 server but before + it is returned to user code. + """ + return response + @dataclasses.dataclass class BinauthzManagementServiceV1Beta1RestStub: @@ -1577,6 +1653,439 @@ def update_policy( # In C++ this would require a dynamic_cast return self._UpdatePolicy(self._session, self._host, self._interceptor) # type: ignore + @property + def get_iam_policy(self): + return self._GetIamPolicy(self._session, self._host, self._interceptor) # type: ignore + + class _GetIamPolicy( + _BaseBinauthzManagementServiceV1Beta1RestTransport._BaseGetIamPolicy, + BinauthzManagementServiceV1Beta1RestStub, + ): + def __hash__(self): + return hash("BinauthzManagementServiceV1Beta1RestTransport.GetIamPolicy") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: iam_policy_pb2.GetIamPolicyRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> policy_pb2.Policy: + r"""Call the get iam policy method over HTTP. + + Args: + request (iam_policy_pb2.GetIamPolicyRequest): + The request object for GetIamPolicy method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + policy_pb2.Policy: Response from GetIamPolicy method. + """ + + http_options = _BaseBinauthzManagementServiceV1Beta1RestTransport._BaseGetIamPolicy._get_http_options() + + request, metadata = self._interceptor.pre_get_iam_policy(request, metadata) + transcoded_request = _BaseBinauthzManagementServiceV1Beta1RestTransport._BaseGetIamPolicy._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = _BaseBinauthzManagementServiceV1Beta1RestTransport._BaseGetIamPolicy._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 = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.binaryauthorization_v1beta1.BinauthzManagementServiceV1Beta1Client.GetIamPolicy", + extra={ + "serviceName": "google.cloud.binaryauthorization.v1beta1.BinauthzManagementServiceV1Beta1", + "rpcName": "GetIamPolicy", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = BinauthzManagementServiceV1Beta1RestTransport._GetIamPolicy._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + content = response.content.decode("utf-8") + resp = policy_pb2.Policy() + resp = json_format.Parse(content, resp) + resp = self._interceptor.post_get_iam_policy(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.binaryauthorization_v1beta1.BinauthzManagementServiceV1Beta1AsyncClient.GetIamPolicy", + extra={ + "serviceName": "google.cloud.binaryauthorization.v1beta1.BinauthzManagementServiceV1Beta1", + "rpcName": "GetIamPolicy", + "httpResponse": http_response, + "metadata": http_response["headers"], + }, + ) + return resp + + @property + def set_iam_policy(self): + return self._SetIamPolicy(self._session, self._host, self._interceptor) # type: ignore + + class _SetIamPolicy( + _BaseBinauthzManagementServiceV1Beta1RestTransport._BaseSetIamPolicy, + BinauthzManagementServiceV1Beta1RestStub, + ): + def __hash__(self): + return hash("BinauthzManagementServiceV1Beta1RestTransport.SetIamPolicy") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: iam_policy_pb2.SetIamPolicyRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> policy_pb2.Policy: + r"""Call the set iam policy method over HTTP. + + Args: + request (iam_policy_pb2.SetIamPolicyRequest): + The request object for SetIamPolicy method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + policy_pb2.Policy: Response from SetIamPolicy method. + """ + + http_options = _BaseBinauthzManagementServiceV1Beta1RestTransport._BaseSetIamPolicy._get_http_options() + + request, metadata = self._interceptor.pre_set_iam_policy(request, metadata) + transcoded_request = _BaseBinauthzManagementServiceV1Beta1RestTransport._BaseSetIamPolicy._get_transcoded_request( + http_options, request + ) + + body = _BaseBinauthzManagementServiceV1Beta1RestTransport._BaseSetIamPolicy._get_request_body_json( + transcoded_request + ) + + # Jsonify the query params + query_params = _BaseBinauthzManagementServiceV1Beta1RestTransport._BaseSetIamPolicy._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 = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.binaryauthorization_v1beta1.BinauthzManagementServiceV1Beta1Client.SetIamPolicy", + extra={ + "serviceName": "google.cloud.binaryauthorization.v1beta1.BinauthzManagementServiceV1Beta1", + "rpcName": "SetIamPolicy", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = BinauthzManagementServiceV1Beta1RestTransport._SetIamPolicy._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + content = response.content.decode("utf-8") + resp = policy_pb2.Policy() + resp = json_format.Parse(content, resp) + resp = self._interceptor.post_set_iam_policy(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.binaryauthorization_v1beta1.BinauthzManagementServiceV1Beta1AsyncClient.SetIamPolicy", + extra={ + "serviceName": "google.cloud.binaryauthorization.v1beta1.BinauthzManagementServiceV1Beta1", + "rpcName": "SetIamPolicy", + "httpResponse": http_response, + "metadata": http_response["headers"], + }, + ) + return resp + + @property + def test_iam_permissions(self): + return self._TestIamPermissions(self._session, self._host, self._interceptor) # type: ignore + + class _TestIamPermissions( + _BaseBinauthzManagementServiceV1Beta1RestTransport._BaseTestIamPermissions, + BinauthzManagementServiceV1Beta1RestStub, + ): + def __hash__(self): + return hash( + "BinauthzManagementServiceV1Beta1RestTransport.TestIamPermissions" + ) + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: iam_policy_pb2.TestIamPermissionsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> iam_policy_pb2.TestIamPermissionsResponse: + r"""Call the test iam permissions method over HTTP. + + Args: + request (iam_policy_pb2.TestIamPermissionsRequest): + The request object for TestIamPermissions method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + iam_policy_pb2.TestIamPermissionsResponse: Response from TestIamPermissions method. + """ + + http_options = _BaseBinauthzManagementServiceV1Beta1RestTransport._BaseTestIamPermissions._get_http_options() + + request, metadata = self._interceptor.pre_test_iam_permissions( + request, metadata + ) + transcoded_request = _BaseBinauthzManagementServiceV1Beta1RestTransport._BaseTestIamPermissions._get_transcoded_request( + http_options, request + ) + + body = _BaseBinauthzManagementServiceV1Beta1RestTransport._BaseTestIamPermissions._get_request_body_json( + transcoded_request + ) + + # Jsonify the query params + query_params = _BaseBinauthzManagementServiceV1Beta1RestTransport._BaseTestIamPermissions._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 = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.binaryauthorization_v1beta1.BinauthzManagementServiceV1Beta1Client.TestIamPermissions", + extra={ + "serviceName": "google.cloud.binaryauthorization.v1beta1.BinauthzManagementServiceV1Beta1", + "rpcName": "TestIamPermissions", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = BinauthzManagementServiceV1Beta1RestTransport._TestIamPermissions._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) + + content = response.content.decode("utf-8") + resp = iam_policy_pb2.TestIamPermissionsResponse() + resp = json_format.Parse(content, resp) + resp = self._interceptor.post_test_iam_permissions(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.binaryauthorization_v1beta1.BinauthzManagementServiceV1Beta1AsyncClient.TestIamPermissions", + extra={ + "serviceName": "google.cloud.binaryauthorization.v1beta1.BinauthzManagementServiceV1Beta1", + "rpcName": "TestIamPermissions", + "httpResponse": http_response, + "metadata": http_response["headers"], + }, + ) + return resp + @property def kind(self) -> str: return "rest" diff --git a/packages/google-cloud-binary-authorization/google/cloud/binaryauthorization_v1beta1/services/binauthz_management_service_v1_beta1/transports/rest_base.py b/packages/google-cloud-binary-authorization/google/cloud/binaryauthorization_v1beta1/services/binauthz_management_service_v1_beta1/transports/rest_base.py index aa262d0fe5a9..f4d65efa3d85 100644 --- a/packages/google-cloud-binary-authorization/google/cloud/binaryauthorization_v1beta1/services/binauthz_management_service_v1_beta1/transports/rest_base.py +++ b/packages/google-cloud-binary-authorization/google/cloud/binaryauthorization_v1beta1/services/binauthz_management_service_v1_beta1/transports/rest_base.py @@ -19,6 +19,10 @@ import google.protobuf.empty_pb2 as empty_pb2 # type: ignore from google.api_core import gapic_v1, path_template +from google.iam.v1 import ( + iam_policy_pb2, # type: ignore + policy_pb2, # type: ignore +) from google.protobuf import json_format from google.cloud.binaryauthorization_v1beta1.types import resources, service @@ -451,5 +455,106 @@ def _get_query_params_json(transcoded_request): query_params["$alt"] = "json;enum-encoding=int" return query_params + class _BaseGetIamPolicy: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1beta1/{resource=projects/*/policy}:getIamPolicy", + }, + { + "method": "get", + "uri": "/v1beta1/{resource=projects/*/attestors/*}:getIamPolicy", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + return query_params + + class _BaseSetIamPolicy: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1beta1/{resource=projects/*/policy}:setIamPolicy", + "body": "*", + }, + { + "method": "post", + "uri": "/v1beta1/{resource=projects/*/attestors/*}:setIamPolicy", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + body = json.dumps(transcoded_request["body"]) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + return query_params + + class _BaseTestIamPermissions: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1beta1/{resource=projects/*/policy}:testIamPermissions", + "body": "*", + }, + { + "method": "post", + "uri": "/v1beta1/{resource=projects/*/attestors/*}:testIamPermissions", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + body = json.dumps(transcoded_request["body"]) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + return query_params + __all__ = ("_BaseBinauthzManagementServiceV1Beta1RestTransport",) diff --git a/packages/google-cloud-binary-authorization/google/cloud/binaryauthorization_v1beta1/services/system_policy_v1_beta1/async_client.py b/packages/google-cloud-binary-authorization/google/cloud/binaryauthorization_v1beta1/services/system_policy_v1_beta1/async_client.py index 7dd441d947cc..7f0a01393347 100644 --- a/packages/google-cloud-binary-authorization/google/cloud/binaryauthorization_v1beta1/services/system_policy_v1_beta1/async_client.py +++ b/packages/google-cloud-binary-authorization/google/cloud/binaryauthorization_v1beta1/services/system_policy_v1_beta1/async_client.py @@ -45,6 +45,10 @@ OptionalRetry = Union[retries.AsyncRetry, object, None] # type: ignore import google.protobuf.timestamp_pb2 as timestamp_pb2 # type: ignore +from google.iam.v1 import ( + iam_policy_pb2, # type: ignore + policy_pb2, # type: ignore +) from google.cloud.binaryauthorization_v1beta1.types import resources, service @@ -360,9 +364,8 @@ async def sample_get_system_policy(): Returns: google.cloud.binaryauthorization_v1beta1.types.Policy: - A - [policy][google.cloud.binaryauthorization.v1beta1.Policy] - for Binary Authorization. + A [policy][google.cloud.binaryauthorization.v1beta1.Policy] for Binary + Authorization. """ # Create or coerce a protobuf request object. @@ -414,6 +417,329 @@ async def sample_get_system_policy(): # Done; return the response. return response + async def set_iam_policy( + self, + request: Optional[Union[iam_policy_pb2.SetIamPolicyRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> policy_pb2.Policy: + r"""Sets the IAM access control policy on the specified function. + + Replaces any existing policy. + + Args: + request (:class:`~.iam_policy_pb2.SetIamPolicyRequest`): + The request object. Request message for `SetIamPolicy` + method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.policy_pb2.Policy: + Defines an Identity and Access Management (IAM) policy. + It is used to specify access control policies for Cloud + Platform resources. + A ``Policy`` is a collection of ``bindings``. A + ``binding`` binds one or more ``members`` to a single + ``role``. Members can be user accounts, service + accounts, Google groups, and domains (such as G Suite). + A ``role`` is a named list of permissions (defined by + IAM or configured by users). A ``binding`` can + optionally specify a ``condition``, which is a logic + expression that further constrains the role binding + based on attributes about the request and/or target + resource. + + **JSON Example** + + :: + + { + "bindings": [ + { + "role": "roles/resourcemanager.organizationAdmin", + "members": [ + "user:mike@example.com", + "group:admins@example.com", + "domain:google.com", + "serviceAccount:my-project-id@appspot.gserviceaccount.com" + ] + }, + { + "role": "roles/resourcemanager.organizationViewer", + "members": ["user:eve@example.com"], + "condition": { + "title": "expirable access", + "description": "Does not grant access after Sep 2020", + "expression": "request.time < + timestamp('2020-10-01T00:00:00.000Z')", + } + } + ] + } + + **YAML Example** + + :: + + bindings: + - members: + - user:mike@example.com + - group:admins@example.com + - domain:google.com + - serviceAccount:my-project-id@appspot.gserviceaccount.com + role: roles/resourcemanager.organizationAdmin + - members: + - user:eve@example.com + role: roles/resourcemanager.organizationViewer + condition: + title: expirable access + description: Does not grant access after Sep 2020 + expression: request.time < timestamp('2020-10-01T00:00:00.000Z') + + For a description of IAM and its features, see the `IAM + developer's + guide `__. + """ + # Create or coerce a protobuf request object. + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if request is None: + request_pb = iam_policy_pb2.SetIamPolicyRequest() + elif isinstance(request, dict): + request_pb = iam_policy_pb2.SetIamPolicyRequest(**request) + else: + request_pb = request + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self.transport._wrapped_methods[self._client._transport.set_iam_policy] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("resource", request_pb.resource),) + ), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_iam_policy( + self, + request: Optional[Union[iam_policy_pb2.GetIamPolicyRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> policy_pb2.Policy: + r"""Gets the IAM access control policy for a function. + + Returns an empty policy if the function exists and does not have a + policy set. + + Args: + request (:class:`~.iam_policy_pb2.GetIamPolicyRequest`): + The request object. Request message for `GetIamPolicy` + method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if + any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.policy_pb2.Policy: + Defines an Identity and Access Management (IAM) policy. + It is used to specify access control policies for Cloud + Platform resources. + A ``Policy`` is a collection of ``bindings``. A + ``binding`` binds one or more ``members`` to a single + ``role``. Members can be user accounts, service + accounts, Google groups, and domains (such as G Suite). + A ``role`` is a named list of permissions (defined by + IAM or configured by users). A ``binding`` can + optionally specify a ``condition``, which is a logic + expression that further constrains the role binding + based on attributes about the request and/or target + resource. + + **JSON Example** + + :: + + { + "bindings": [ + { + "role": "roles/resourcemanager.organizationAdmin", + "members": [ + "user:mike@example.com", + "group:admins@example.com", + "domain:google.com", + "serviceAccount:my-project-id@appspot.gserviceaccount.com" + ] + }, + { + "role": "roles/resourcemanager.organizationViewer", + "members": ["user:eve@example.com"], + "condition": { + "title": "expirable access", + "description": "Does not grant access after Sep 2020", + "expression": "request.time < + timestamp('2020-10-01T00:00:00.000Z')", + } + } + ] + } + + **YAML Example** + + :: + + bindings: + - members: + - user:mike@example.com + - group:admins@example.com + - domain:google.com + - serviceAccount:my-project-id@appspot.gserviceaccount.com + role: roles/resourcemanager.organizationAdmin + - members: + - user:eve@example.com + role: roles/resourcemanager.organizationViewer + condition: + title: expirable access + description: Does not grant access after Sep 2020 + expression: request.time < timestamp('2020-10-01T00:00:00.000Z') + + For a description of IAM and its features, see the `IAM + developer's + guide `__. + """ + # Create or coerce a protobuf request object. + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if request is None: + request_pb = iam_policy_pb2.GetIamPolicyRequest() + elif isinstance(request, dict): + request_pb = iam_policy_pb2.GetIamPolicyRequest(**request) + else: + request_pb = request + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self.transport._wrapped_methods[self._client._transport.get_iam_policy] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("resource", request_pb.resource),) + ), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def test_iam_permissions( + self, + request: Optional[Union[iam_policy_pb2.TestIamPermissionsRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> iam_policy_pb2.TestIamPermissionsResponse: + r"""Tests the specified IAM permissions against the IAM access control + policy for a function. + + If the function does not exist, this will return an empty set + of permissions, not a NOT_FOUND error. + + Args: + request (:class:`~.iam_policy_pb2.TestIamPermissionsRequest`): + The request object. Request message for + `TestIamPermissions` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.iam_policy_pb2.TestIamPermissionsResponse: + Response message for ``TestIamPermissions`` method. + """ + # Create or coerce a protobuf request object. + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if request is None: + request_pb = iam_policy_pb2.TestIamPermissionsRequest() + elif isinstance(request, dict): + request_pb = iam_policy_pb2.TestIamPermissionsRequest(**request) + else: + request_pb = request + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self.transport._wrapped_methods[ + self._client._transport.test_iam_permissions + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("resource", request_pb.resource),) + ), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + async def __aenter__(self) -> "SystemPolicyV1Beta1AsyncClient": return self diff --git a/packages/google-cloud-binary-authorization/google/cloud/binaryauthorization_v1beta1/services/system_policy_v1_beta1/client.py b/packages/google-cloud-binary-authorization/google/cloud/binaryauthorization_v1beta1/services/system_policy_v1_beta1/client.py index 675d75235c9b..d8d0f3a6a585 100644 --- a/packages/google-cloud-binary-authorization/google/cloud/binaryauthorization_v1beta1/services/system_policy_v1_beta1/client.py +++ b/packages/google-cloud-binary-authorization/google/cloud/binaryauthorization_v1beta1/services/system_policy_v1_beta1/client.py @@ -62,6 +62,10 @@ _LOGGER = std_logging.getLogger(__name__) import google.protobuf.timestamp_pb2 as timestamp_pb2 # type: ignore +from google.iam.v1 import ( + iam_policy_pb2, # type: ignore + policy_pb2, # type: ignore +) from google.cloud.binaryauthorization_v1beta1.types import resources, service @@ -786,9 +790,8 @@ def sample_get_system_policy(): Returns: google.cloud.binaryauthorization_v1beta1.types.Policy: - A - [policy][google.cloud.binaryauthorization.v1beta1.Policy] - for Binary Authorization. + A [policy][google.cloud.binaryauthorization.v1beta1.Policy] for Binary + Authorization. """ # Create or coerce a protobuf request object. @@ -850,6 +853,339 @@ def __exit__(self, type, value, traceback): """ self.transport.close() + def set_iam_policy( + self, + request: Optional[Union[iam_policy_pb2.SetIamPolicyRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> policy_pb2.Policy: + r"""Sets the IAM access control policy on the specified function. + + Replaces any existing policy. + + Args: + request (:class:`~.iam_policy_pb2.SetIamPolicyRequest`): + The request object. Request message for `SetIamPolicy` + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.policy_pb2.Policy: + Defines an Identity and Access Management (IAM) policy. + It is used to specify access control policies for Cloud + Platform resources. + A ``Policy`` is a collection of ``bindings``. A + ``binding`` binds one or more ``members`` to a single + ``role``. Members can be user accounts, service + accounts, Google groups, and domains (such as G Suite). + A ``role`` is a named list of permissions (defined by + IAM or configured by users). A ``binding`` can + optionally specify a ``condition``, which is a logic + expression that further constrains the role binding + based on attributes about the request and/or target + resource. + + **JSON Example** + + :: + + { + "bindings": [ + { + "role": "roles/resourcemanager.organizationAdmin", + "members": [ + "user:mike@example.com", + "group:admins@example.com", + "domain:google.com", + "serviceAccount:my-project-id@appspot.gserviceaccount.com" + ] + }, + { + "role": "roles/resourcemanager.organizationViewer", + "members": ["user:eve@example.com"], + "condition": { + "title": "expirable access", + "description": "Does not grant access after Sep 2020", + "expression": "request.time < + timestamp('2020-10-01T00:00:00.000Z')", + } + } + ] + } + + **YAML Example** + + :: + + bindings: + - members: + - user:mike@example.com + - group:admins@example.com + - domain:google.com + - serviceAccount:my-project-id@appspot.gserviceaccount.com + role: roles/resourcemanager.organizationAdmin + - members: + - user:eve@example.com + role: roles/resourcemanager.organizationViewer + condition: + title: expirable access + description: Does not grant access after Sep 2020 + expression: request.time < timestamp('2020-10-01T00:00:00.000Z') + + For a description of IAM and its features, see the `IAM + developer's + guide `__. + """ + # Create or coerce a protobuf request object. + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if request is None: + request_pb = iam_policy_pb2.SetIamPolicyRequest() + elif isinstance(request, dict): + request_pb = iam_policy_pb2.SetIamPolicyRequest(**request) + else: + request_pb = request + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.set_iam_policy] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("resource", request_pb.resource),) + ), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + try: + # Send the request. + response = rpc( + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + except core_exceptions.GoogleAPICallError as e: + self._add_cred_info_for_auth_errors(e) + raise e + + def get_iam_policy( + self, + request: Optional[Union[iam_policy_pb2.GetIamPolicyRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> policy_pb2.Policy: + r"""Gets the IAM access control policy for a function. + + Returns an empty policy if the function exists and does not have a + policy set. + + Args: + request (:class:`~.iam_policy_pb2.GetIamPolicyRequest`): + The request object. Request message for `GetIamPolicy` + method. + retry (google.api_core.retry.Retry): Designation of what errors, if + any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.policy_pb2.Policy: + Defines an Identity and Access Management (IAM) policy. + It is used to specify access control policies for Cloud + Platform resources. + A ``Policy`` is a collection of ``bindings``. A + ``binding`` binds one or more ``members`` to a single + ``role``. Members can be user accounts, service + accounts, Google groups, and domains (such as G Suite). + A ``role`` is a named list of permissions (defined by + IAM or configured by users). A ``binding`` can + optionally specify a ``condition``, which is a logic + expression that further constrains the role binding + based on attributes about the request and/or target + resource. + + **JSON Example** + + :: + + { + "bindings": [ + { + "role": "roles/resourcemanager.organizationAdmin", + "members": [ + "user:mike@example.com", + "group:admins@example.com", + "domain:google.com", + "serviceAccount:my-project-id@appspot.gserviceaccount.com" + ] + }, + { + "role": "roles/resourcemanager.organizationViewer", + "members": ["user:eve@example.com"], + "condition": { + "title": "expirable access", + "description": "Does not grant access after Sep 2020", + "expression": "request.time < + timestamp('2020-10-01T00:00:00.000Z')", + } + } + ] + } + + **YAML Example** + + :: + + bindings: + - members: + - user:mike@example.com + - group:admins@example.com + - domain:google.com + - serviceAccount:my-project-id@appspot.gserviceaccount.com + role: roles/resourcemanager.organizationAdmin + - members: + - user:eve@example.com + role: roles/resourcemanager.organizationViewer + condition: + title: expirable access + description: Does not grant access after Sep 2020 + expression: request.time < timestamp('2020-10-01T00:00:00.000Z') + + For a description of IAM and its features, see the `IAM + developer's + guide `__. + """ + # Create or coerce a protobuf request object. + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if request is None: + request_pb = iam_policy_pb2.GetIamPolicyRequest() + elif isinstance(request, dict): + request_pb = iam_policy_pb2.GetIamPolicyRequest(**request) + else: + request_pb = request + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_iam_policy] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("resource", request_pb.resource),) + ), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + try: + # Send the request. + response = rpc( + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + except core_exceptions.GoogleAPICallError as e: + self._add_cred_info_for_auth_errors(e) + raise e + + def test_iam_permissions( + self, + request: Optional[Union[iam_policy_pb2.TestIamPermissionsRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> iam_policy_pb2.TestIamPermissionsResponse: + r"""Tests the specified IAM permissions against the IAM access control + policy for a function. + + If the function does not exist, this will return an empty set + of permissions, not a NOT_FOUND error. + + Args: + request (:class:`~.iam_policy_pb2.TestIamPermissionsRequest`): + The request object. Request message for + `TestIamPermissions` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.iam_policy_pb2.TestIamPermissionsResponse: + Response message for ``TestIamPermissions`` method. + """ + # Create or coerce a protobuf request object. + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if request is None: + request_pb = iam_policy_pb2.TestIamPermissionsRequest() + elif isinstance(request, dict): + request_pb = iam_policy_pb2.TestIamPermissionsRequest(**request) + else: + request_pb = request + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.test_iam_permissions] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("resource", request_pb.resource),) + ), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + try: + # Send the request. + response = rpc( + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + except core_exceptions.GoogleAPICallError as e: + self._add_cred_info_for_auth_errors(e) + raise e + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( gapic_version=package_version.__version__ diff --git a/packages/google-cloud-binary-authorization/google/cloud/binaryauthorization_v1beta1/services/system_policy_v1_beta1/transports/base.py b/packages/google-cloud-binary-authorization/google/cloud/binaryauthorization_v1beta1/services/system_policy_v1_beta1/transports/base.py index 3e08d7b25ed2..63e832342394 100644 --- a/packages/google-cloud-binary-authorization/google/cloud/binaryauthorization_v1beta1/services/system_policy_v1_beta1/transports/base.py +++ b/packages/google-cloud-binary-authorization/google/cloud/binaryauthorization_v1beta1/services/system_policy_v1_beta1/transports/base.py @@ -23,6 +23,10 @@ from google.api_core import gapic_v1 from google.api_core import retry as retries from google.auth import credentials as ga_credentials # type: ignore +from google.iam.v1 import ( + iam_policy_pb2, # type: ignore + policy_pb2, # type: ignore +) from google.oauth2 import service_account # type: ignore from google.cloud.binaryauthorization_v1beta1 import gapic_version as package_version @@ -147,6 +151,21 @@ def _prep_wrapped_messages(self, client_info): default_timeout=None, client_info=client_info, ), + self.get_iam_policy: gapic_v1.method.wrap_method( + self.get_iam_policy, + default_timeout=None, + client_info=client_info, + ), + self.set_iam_policy: gapic_v1.method.wrap_method( + self.set_iam_policy, + default_timeout=None, + client_info=client_info, + ), + self.test_iam_permissions: gapic_v1.method.wrap_method( + self.test_iam_permissions, + default_timeout=None, + client_info=client_info, + ), } def close(self): @@ -167,6 +186,36 @@ def get_system_policy( ]: raise NotImplementedError() + @property + def set_iam_policy( + self, + ) -> Callable[ + [iam_policy_pb2.SetIamPolicyRequest], + Union[policy_pb2.Policy, Awaitable[policy_pb2.Policy]], + ]: + raise NotImplementedError() + + @property + def get_iam_policy( + self, + ) -> Callable[ + [iam_policy_pb2.GetIamPolicyRequest], + Union[policy_pb2.Policy, Awaitable[policy_pb2.Policy]], + ]: + raise NotImplementedError() + + @property + def test_iam_permissions( + self, + ) -> Callable[ + [iam_policy_pb2.TestIamPermissionsRequest], + Union[ + iam_policy_pb2.TestIamPermissionsResponse, + Awaitable[iam_policy_pb2.TestIamPermissionsResponse], + ], + ]: + raise NotImplementedError() + @property def kind(self) -> str: raise NotImplementedError() diff --git a/packages/google-cloud-binary-authorization/google/cloud/binaryauthorization_v1beta1/services/system_policy_v1_beta1/transports/grpc.py b/packages/google-cloud-binary-authorization/google/cloud/binaryauthorization_v1beta1/services/system_policy_v1_beta1/transports/grpc.py index ef9ff903bbf9..6eb027c8670f 100644 --- a/packages/google-cloud-binary-authorization/google/cloud/binaryauthorization_v1beta1/services/system_policy_v1_beta1/transports/grpc.py +++ b/packages/google-cloud-binary-authorization/google/cloud/binaryauthorization_v1beta1/services/system_policy_v1_beta1/transports/grpc.py @@ -26,6 +26,10 @@ from google.api_core import gapic_v1, grpc_helpers from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore +from google.iam.v1 import ( + iam_policy_pb2, # type: ignore + policy_pb2, # type: ignore +) from google.protobuf.json_format import MessageToJson from google.cloud.binaryauthorization_v1beta1.types import resources, service @@ -355,6 +359,86 @@ def get_system_policy( def close(self): self._logged_channel.close() + @property + def set_iam_policy( + self, + ) -> Callable[[iam_policy_pb2.SetIamPolicyRequest], policy_pb2.Policy]: + r"""Return a callable for the set iam policy method over gRPC. + Sets the IAM access control policy on the specified + function. Replaces any existing policy. + Returns: + Callable[[~.SetIamPolicyRequest], + ~.Policy]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "set_iam_policy" not in self._stubs: + self._stubs["set_iam_policy"] = self._logged_channel.unary_unary( + "/google.iam.v1.IAMPolicy/SetIamPolicy", + request_serializer=iam_policy_pb2.SetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs["set_iam_policy"] + + @property + def get_iam_policy( + self, + ) -> Callable[[iam_policy_pb2.GetIamPolicyRequest], policy_pb2.Policy]: + r"""Return a callable for the get iam policy method over gRPC. + Gets the IAM access control policy for a function. + Returns an empty policy if the function exists and does + not have a policy set. + Returns: + Callable[[~.GetIamPolicyRequest], + ~.Policy]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_iam_policy" not in self._stubs: + self._stubs["get_iam_policy"] = self._logged_channel.unary_unary( + "/google.iam.v1.IAMPolicy/GetIamPolicy", + request_serializer=iam_policy_pb2.GetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs["get_iam_policy"] + + @property + def test_iam_permissions( + self, + ) -> Callable[ + [iam_policy_pb2.TestIamPermissionsRequest], + iam_policy_pb2.TestIamPermissionsResponse, + ]: + r"""Return a callable for the test iam permissions method over gRPC. + Tests the specified permissions against the IAM access control + policy for a function. If the function does not exist, this will + return an empty set of permissions, not a NOT_FOUND error. + Returns: + Callable[[~.TestIamPermissionsRequest], + ~.TestIamPermissionsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "test_iam_permissions" not in self._stubs: + self._stubs["test_iam_permissions"] = self._logged_channel.unary_unary( + "/google.iam.v1.IAMPolicy/TestIamPermissions", + request_serializer=iam_policy_pb2.TestIamPermissionsRequest.SerializeToString, + response_deserializer=iam_policy_pb2.TestIamPermissionsResponse.FromString, + ) + return self._stubs["test_iam_permissions"] + @property def kind(self) -> str: return "grpc" diff --git a/packages/google-cloud-binary-authorization/google/cloud/binaryauthorization_v1beta1/services/system_policy_v1_beta1/transports/grpc_asyncio.py b/packages/google-cloud-binary-authorization/google/cloud/binaryauthorization_v1beta1/services/system_policy_v1_beta1/transports/grpc_asyncio.py index 60d7885d8b83..bf20cce4ad73 100644 --- a/packages/google-cloud-binary-authorization/google/cloud/binaryauthorization_v1beta1/services/system_policy_v1_beta1/transports/grpc_asyncio.py +++ b/packages/google-cloud-binary-authorization/google/cloud/binaryauthorization_v1beta1/services/system_policy_v1_beta1/transports/grpc_asyncio.py @@ -28,6 +28,10 @@ from google.api_core import retry_async as retries from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore +from google.iam.v1 import ( + iam_policy_pb2, # type: ignore + policy_pb2, # type: ignore +) from google.protobuf.json_format import MessageToJson from grpc.experimental import aio # type: ignore @@ -368,6 +372,21 @@ def _prep_wrapped_messages(self, client_info): default_timeout=None, client_info=client_info, ), + self.get_iam_policy: self._wrap_method( + self.get_iam_policy, + default_timeout=None, + client_info=client_info, + ), + self.set_iam_policy: self._wrap_method( + self.set_iam_policy, + default_timeout=None, + client_info=client_info, + ), + self.test_iam_permissions: self._wrap_method( + self.test_iam_permissions, + default_timeout=None, + client_info=client_info, + ), } def _wrap_method(self, func, *args, **kwargs): @@ -382,5 +401,85 @@ def close(self): def kind(self) -> str: return "grpc_asyncio" + @property + def set_iam_policy( + self, + ) -> Callable[[iam_policy_pb2.SetIamPolicyRequest], policy_pb2.Policy]: + r"""Return a callable for the set iam policy method over gRPC. + Sets the IAM access control policy on the specified + function. Replaces any existing policy. + Returns: + Callable[[~.SetIamPolicyRequest], + ~.Policy]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "set_iam_policy" not in self._stubs: + self._stubs["set_iam_policy"] = self._logged_channel.unary_unary( + "/google.iam.v1.IAMPolicy/SetIamPolicy", + request_serializer=iam_policy_pb2.SetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs["set_iam_policy"] + + @property + def get_iam_policy( + self, + ) -> Callable[[iam_policy_pb2.GetIamPolicyRequest], policy_pb2.Policy]: + r"""Return a callable for the get iam policy method over gRPC. + Gets the IAM access control policy for a function. + Returns an empty policy if the function exists and does + not have a policy set. + Returns: + Callable[[~.GetIamPolicyRequest], + ~.Policy]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_iam_policy" not in self._stubs: + self._stubs["get_iam_policy"] = self._logged_channel.unary_unary( + "/google.iam.v1.IAMPolicy/GetIamPolicy", + request_serializer=iam_policy_pb2.GetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs["get_iam_policy"] + + @property + def test_iam_permissions( + self, + ) -> Callable[ + [iam_policy_pb2.TestIamPermissionsRequest], + iam_policy_pb2.TestIamPermissionsResponse, + ]: + r"""Return a callable for the test iam permissions method over gRPC. + Tests the specified permissions against the IAM access control + policy for a function. If the function does not exist, this will + return an empty set of permissions, not a NOT_FOUND error. + Returns: + Callable[[~.TestIamPermissionsRequest], + ~.TestIamPermissionsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "test_iam_permissions" not in self._stubs: + self._stubs["test_iam_permissions"] = self._logged_channel.unary_unary( + "/google.iam.v1.IAMPolicy/TestIamPermissions", + request_serializer=iam_policy_pb2.TestIamPermissionsRequest.SerializeToString, + response_deserializer=iam_policy_pb2.TestIamPermissionsResponse.FromString, + ) + return self._stubs["test_iam_permissions"] + __all__ = ("SystemPolicyV1Beta1GrpcAsyncIOTransport",) diff --git a/packages/google-cloud-binary-authorization/google/cloud/binaryauthorization_v1beta1/services/system_policy_v1_beta1/transports/rest.py b/packages/google-cloud-binary-authorization/google/cloud/binaryauthorization_v1beta1/services/system_policy_v1_beta1/transports/rest.py index 2f790da11dce..7a1046f2e7de 100644 --- a/packages/google-cloud-binary-authorization/google/cloud/binaryauthorization_v1beta1/services/system_policy_v1_beta1/transports/rest.py +++ b/packages/google-cloud-binary-authorization/google/cloud/binaryauthorization_v1beta1/services/system_policy_v1_beta1/transports/rest.py @@ -25,6 +25,10 @@ from google.api_core import retry as retries from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.requests import AuthorizedSession # type: ignore +from google.iam.v1 import ( + iam_policy_pb2, # type: ignore + policy_pb2, # type: ignore +) from google.protobuf import json_format from requests import __version__ as requests_version @@ -130,6 +134,78 @@ def post_get_system_policy_with_metadata( """ return response, metadata + def pre_get_iam_policy( + self, + request: iam_policy_pb2.GetIamPolicyRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + iam_policy_pb2.GetIamPolicyRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for get_iam_policy + + Override in a subclass to manipulate the request or metadata + before they are sent to the SystemPolicyV1Beta1 server. + """ + return request, metadata + + def post_get_iam_policy(self, response: policy_pb2.Policy) -> policy_pb2.Policy: + """Post-rpc interceptor for get_iam_policy + + Override in a subclass to manipulate the response + after it is returned by the SystemPolicyV1Beta1 server but before + it is returned to user code. + """ + return response + + def pre_set_iam_policy( + self, + request: iam_policy_pb2.SetIamPolicyRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + iam_policy_pb2.SetIamPolicyRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for set_iam_policy + + Override in a subclass to manipulate the request or metadata + before they are sent to the SystemPolicyV1Beta1 server. + """ + return request, metadata + + def post_set_iam_policy(self, response: policy_pb2.Policy) -> policy_pb2.Policy: + """Post-rpc interceptor for set_iam_policy + + Override in a subclass to manipulate the response + after it is returned by the SystemPolicyV1Beta1 server but before + it is returned to user code. + """ + return response + + def pre_test_iam_permissions( + self, + request: iam_policy_pb2.TestIamPermissionsRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + iam_policy_pb2.TestIamPermissionsRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for test_iam_permissions + + Override in a subclass to manipulate the request or metadata + before they are sent to the SystemPolicyV1Beta1 server. + """ + return request, metadata + + def post_test_iam_permissions( + self, response: iam_policy_pb2.TestIamPermissionsResponse + ) -> iam_policy_pb2.TestIamPermissionsResponse: + """Post-rpc interceptor for test_iam_permissions + + Override in a subclass to manipulate the response + after it is returned by the SystemPolicyV1Beta1 server but before + it is returned to user code. + """ + return response + @dataclasses.dataclass class SystemPolicyV1Beta1RestStub: @@ -381,6 +457,439 @@ def get_system_policy( # In C++ this would require a dynamic_cast return self._GetSystemPolicy(self._session, self._host, self._interceptor) # type: ignore + @property + def get_iam_policy(self): + return self._GetIamPolicy(self._session, self._host, self._interceptor) # type: ignore + + class _GetIamPolicy( + _BaseSystemPolicyV1Beta1RestTransport._BaseGetIamPolicy, + SystemPolicyV1Beta1RestStub, + ): + def __hash__(self): + return hash("SystemPolicyV1Beta1RestTransport.GetIamPolicy") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: iam_policy_pb2.GetIamPolicyRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> policy_pb2.Policy: + r"""Call the get iam policy method over HTTP. + + Args: + request (iam_policy_pb2.GetIamPolicyRequest): + The request object for GetIamPolicy method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + policy_pb2.Policy: Response from GetIamPolicy method. + """ + + http_options = _BaseSystemPolicyV1Beta1RestTransport._BaseGetIamPolicy._get_http_options() + + request, metadata = self._interceptor.pre_get_iam_policy(request, metadata) + transcoded_request = _BaseSystemPolicyV1Beta1RestTransport._BaseGetIamPolicy._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = _BaseSystemPolicyV1Beta1RestTransport._BaseGetIamPolicy._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 = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.binaryauthorization_v1beta1.SystemPolicyV1Beta1Client.GetIamPolicy", + extra={ + "serviceName": "google.cloud.binaryauthorization.v1beta1.SystemPolicyV1Beta1", + "rpcName": "GetIamPolicy", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = SystemPolicyV1Beta1RestTransport._GetIamPolicy._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + content = response.content.decode("utf-8") + resp = policy_pb2.Policy() + resp = json_format.Parse(content, resp) + resp = self._interceptor.post_get_iam_policy(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.binaryauthorization_v1beta1.SystemPolicyV1Beta1AsyncClient.GetIamPolicy", + extra={ + "serviceName": "google.cloud.binaryauthorization.v1beta1.SystemPolicyV1Beta1", + "rpcName": "GetIamPolicy", + "httpResponse": http_response, + "metadata": http_response["headers"], + }, + ) + return resp + + @property + def set_iam_policy(self): + return self._SetIamPolicy(self._session, self._host, self._interceptor) # type: ignore + + class _SetIamPolicy( + _BaseSystemPolicyV1Beta1RestTransport._BaseSetIamPolicy, + SystemPolicyV1Beta1RestStub, + ): + def __hash__(self): + return hash("SystemPolicyV1Beta1RestTransport.SetIamPolicy") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: iam_policy_pb2.SetIamPolicyRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> policy_pb2.Policy: + r"""Call the set iam policy method over HTTP. + + Args: + request (iam_policy_pb2.SetIamPolicyRequest): + The request object for SetIamPolicy method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + policy_pb2.Policy: Response from SetIamPolicy method. + """ + + http_options = _BaseSystemPolicyV1Beta1RestTransport._BaseSetIamPolicy._get_http_options() + + request, metadata = self._interceptor.pre_set_iam_policy(request, metadata) + transcoded_request = _BaseSystemPolicyV1Beta1RestTransport._BaseSetIamPolicy._get_transcoded_request( + http_options, request + ) + + body = _BaseSystemPolicyV1Beta1RestTransport._BaseSetIamPolicy._get_request_body_json( + transcoded_request + ) + + # Jsonify the query params + query_params = _BaseSystemPolicyV1Beta1RestTransport._BaseSetIamPolicy._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 = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.binaryauthorization_v1beta1.SystemPolicyV1Beta1Client.SetIamPolicy", + extra={ + "serviceName": "google.cloud.binaryauthorization.v1beta1.SystemPolicyV1Beta1", + "rpcName": "SetIamPolicy", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = SystemPolicyV1Beta1RestTransport._SetIamPolicy._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + content = response.content.decode("utf-8") + resp = policy_pb2.Policy() + resp = json_format.Parse(content, resp) + resp = self._interceptor.post_set_iam_policy(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.binaryauthorization_v1beta1.SystemPolicyV1Beta1AsyncClient.SetIamPolicy", + extra={ + "serviceName": "google.cloud.binaryauthorization.v1beta1.SystemPolicyV1Beta1", + "rpcName": "SetIamPolicy", + "httpResponse": http_response, + "metadata": http_response["headers"], + }, + ) + return resp + + @property + def test_iam_permissions(self): + return self._TestIamPermissions(self._session, self._host, self._interceptor) # type: ignore + + class _TestIamPermissions( + _BaseSystemPolicyV1Beta1RestTransport._BaseTestIamPermissions, + SystemPolicyV1Beta1RestStub, + ): + def __hash__(self): + return hash("SystemPolicyV1Beta1RestTransport.TestIamPermissions") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: iam_policy_pb2.TestIamPermissionsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> iam_policy_pb2.TestIamPermissionsResponse: + r"""Call the test iam permissions method over HTTP. + + Args: + request (iam_policy_pb2.TestIamPermissionsRequest): + The request object for TestIamPermissions method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + iam_policy_pb2.TestIamPermissionsResponse: Response from TestIamPermissions method. + """ + + http_options = _BaseSystemPolicyV1Beta1RestTransport._BaseTestIamPermissions._get_http_options() + + request, metadata = self._interceptor.pre_test_iam_permissions( + request, metadata + ) + transcoded_request = _BaseSystemPolicyV1Beta1RestTransport._BaseTestIamPermissions._get_transcoded_request( + http_options, request + ) + + body = _BaseSystemPolicyV1Beta1RestTransport._BaseTestIamPermissions._get_request_body_json( + transcoded_request + ) + + # Jsonify the query params + query_params = _BaseSystemPolicyV1Beta1RestTransport._BaseTestIamPermissions._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 = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.binaryauthorization_v1beta1.SystemPolicyV1Beta1Client.TestIamPermissions", + extra={ + "serviceName": "google.cloud.binaryauthorization.v1beta1.SystemPolicyV1Beta1", + "rpcName": "TestIamPermissions", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = ( + SystemPolicyV1Beta1RestTransport._TestIamPermissions._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) + + content = response.content.decode("utf-8") + resp = iam_policy_pb2.TestIamPermissionsResponse() + resp = json_format.Parse(content, resp) + resp = self._interceptor.post_test_iam_permissions(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.binaryauthorization_v1beta1.SystemPolicyV1Beta1AsyncClient.TestIamPermissions", + extra={ + "serviceName": "google.cloud.binaryauthorization.v1beta1.SystemPolicyV1Beta1", + "rpcName": "TestIamPermissions", + "httpResponse": http_response, + "metadata": http_response["headers"], + }, + ) + return resp + @property def kind(self) -> str: return "rest" diff --git a/packages/google-cloud-binary-authorization/google/cloud/binaryauthorization_v1beta1/services/system_policy_v1_beta1/transports/rest_base.py b/packages/google-cloud-binary-authorization/google/cloud/binaryauthorization_v1beta1/services/system_policy_v1_beta1/transports/rest_base.py index 855a5e31fd8e..b56caaf5cb05 100644 --- a/packages/google-cloud-binary-authorization/google/cloud/binaryauthorization_v1beta1/services/system_policy_v1_beta1/transports/rest_base.py +++ b/packages/google-cloud-binary-authorization/google/cloud/binaryauthorization_v1beta1/services/system_policy_v1_beta1/transports/rest_base.py @@ -18,6 +18,10 @@ from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union from google.api_core import gapic_v1, path_template +from google.iam.v1 import ( + iam_policy_pb2, # type: ignore + policy_pb2, # type: ignore +) from google.protobuf import json_format from google.cloud.binaryauthorization_v1beta1.types import resources, service @@ -134,5 +138,106 @@ def _get_query_params_json(transcoded_request): query_params["$alt"] = "json;enum-encoding=int" return query_params + class _BaseGetIamPolicy: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1beta1/{resource=projects/*/policy}:getIamPolicy", + }, + { + "method": "get", + "uri": "/v1beta1/{resource=projects/*/attestors/*}:getIamPolicy", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + return query_params + + class _BaseSetIamPolicy: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1beta1/{resource=projects/*/policy}:setIamPolicy", + "body": "*", + }, + { + "method": "post", + "uri": "/v1beta1/{resource=projects/*/attestors/*}:setIamPolicy", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + body = json.dumps(transcoded_request["body"]) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + return query_params + + class _BaseTestIamPermissions: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1beta1/{resource=projects/*/policy}:testIamPermissions", + "body": "*", + }, + { + "method": "post", + "uri": "/v1beta1/{resource=projects/*/attestors/*}:testIamPermissions", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + body = json.dumps(transcoded_request["body"]) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + return query_params + __all__ = ("_BaseSystemPolicyV1Beta1RestTransport",) diff --git a/packages/google-cloud-binary-authorization/google/cloud/binaryauthorization_v1beta1/types/resources.py b/packages/google-cloud-binary-authorization/google/cloud/binaryauthorization_v1beta1/types/resources.py index 5875a8b1e8b1..312b8a2f8a9c 100644 --- a/packages/google-cloud-binary-authorization/google/cloud/binaryauthorization_v1beta1/types/resources.py +++ b/packages/google-cloud-binary-authorization/google/cloud/binaryauthorization_v1beta1/types/resources.py @@ -87,6 +87,12 @@ class Policy(proto.Message): update_time (google.protobuf.timestamp_pb2.Timestamp): Output only. Time when the policy was last updated. + etag (str): + Optional. A checksum, returned by the server, + that can be sent on update requests to ensure + the policy has an up-to-date value before + attempting to update it. See + https://google.aip.dev/154. """ class GlobalPolicyEvaluationMode(proto.Enum): @@ -165,6 +171,10 @@ class GlobalPolicyEvaluationMode(proto.Enum): number=5, message=timestamp_pb2.Timestamp, ) + etag: str = proto.Field( + proto.STRING, + number=11, + ) class AdmissionWhitelistPattern(proto.Message): @@ -210,16 +220,7 @@ class AdmissionRule(proto.Message): Required. How this admission rule will be evaluated. require_attestations_by (MutableSequence[str]): - Optional. The resource names of the attestors that must - attest to a container image, in the format - ``projects/*/attestors/*``. Each attestor must exist before - a policy can reference it. To add an attestor to a policy - the principal issuing the policy change request must be able - to read the attestor resource. - - Note: this field must be non-empty when the evaluation_mode - field specifies REQUIRE_ATTESTATION, otherwise it must be - empty. + enforcement_mode (google.cloud.binaryauthorization_v1beta1.types.AdmissionRule.EnforcementMode): Required. The action when a pod creation is denied by the admission rule. @@ -247,8 +248,10 @@ class EvaluationMode(proto.Enum): ALWAYS_DENY = 3 class EnforcementMode(proto.Enum): - r"""Defines the possible actions when a pod creation is denied by - an admission rule. + r"""TODO(wietse) re-word this text to 'per-image' instead of + 'per-pod' and to allow for three-way evaluation (allow, deny, + delegate). Defines the possible actions when a pod creation is + denied by an admission rule. Values: ENFORCEMENT_MODE_UNSPECIFIED (0): @@ -305,6 +308,12 @@ class Attestor(proto.Message): update_time (google.protobuf.timestamp_pb2.Timestamp): Output only. Time when the attestor was last updated. + etag (str): + Optional. A checksum, returned by the server, + that can be sent on update requests to ensure + the attestor has an up-to-date value before + attempting to update it. See + https://google.aip.dev/154. """ name: str = proto.Field( @@ -326,6 +335,10 @@ class Attestor(proto.Message): number=4, message=timestamp_pb2.Timestamp, ) + etag: str = proto.Field( + proto.STRING, + number=7, + ) class UserOwnedDrydockNote(proto.Message): @@ -417,12 +430,20 @@ class SignatureAlgorithm(proto.Enum): Not specified. RSA_PSS_2048_SHA256 (1): RSASSA-PSS 2048 bit key with a SHA256 digest. + RSA_SIGN_PSS_2048_SHA256 (1): + RSASSA-PSS 2048 bit key with a SHA256 digest. RSA_PSS_3072_SHA256 (2): RSASSA-PSS 3072 bit key with a SHA256 digest. + RSA_SIGN_PSS_3072_SHA256 (2): + RSASSA-PSS 3072 bit key with a SHA256 digest. RSA_PSS_4096_SHA256 (3): RSASSA-PSS 4096 bit key with a SHA256 digest. + RSA_SIGN_PSS_4096_SHA256 (3): + RSASSA-PSS 4096 bit key with a SHA256 digest. RSA_PSS_4096_SHA512 (4): RSASSA-PSS 4096 bit key with a SHA512 digest. + RSA_SIGN_PSS_4096_SHA512 (4): + RSASSA-PSS 4096 bit key with a SHA512 digest. RSA_SIGN_PKCS1_2048_SHA256 (5): RSASSA-PKCS1-v1_5 with a 2048 bit key and a SHA256 digest. RSA_SIGN_PKCS1_3072_SHA256 (6): @@ -449,14 +470,21 @@ class SignatureAlgorithm(proto.Enum): EC_SIGN_P521_SHA512 (11): ECDSA on the NIST P-521 curve with a SHA512 digest. + ML_DSA_65 (13): + ML-DSA-65 Post-Quantum Cryptography signature + algorithm. """ _pb_options = {"allow_alias": True} SIGNATURE_ALGORITHM_UNSPECIFIED = 0 RSA_PSS_2048_SHA256 = 1 + RSA_SIGN_PSS_2048_SHA256 = 1 RSA_PSS_3072_SHA256 = 2 + RSA_SIGN_PSS_3072_SHA256 = 2 RSA_PSS_4096_SHA256 = 3 + RSA_SIGN_PSS_4096_SHA256 = 3 RSA_PSS_4096_SHA512 = 4 + RSA_SIGN_PSS_4096_SHA512 = 4 RSA_SIGN_PKCS1_2048_SHA256 = 5 RSA_SIGN_PKCS1_3072_SHA256 = 6 RSA_SIGN_PKCS1_4096_SHA256 = 7 @@ -467,6 +495,7 @@ class SignatureAlgorithm(proto.Enum): EC_SIGN_P384_SHA384 = 10 ECDSA_P521_SHA512 = 11 EC_SIGN_P521_SHA512 = 11 + ML_DSA_65 = 13 public_key_pem: str = proto.Field( proto.STRING, diff --git a/packages/google-cloud-binary-authorization/tests/unit/gapic/binaryauthorization_v1beta1/test_binauthz_management_service_v1_beta1.py b/packages/google-cloud-binary-authorization/tests/unit/gapic/binaryauthorization_v1beta1/test_binauthz_management_service_v1_beta1.py index e0bdc08172d1..0d50ed520dc9 100644 --- a/packages/google-cloud-binary-authorization/tests/unit/gapic/binaryauthorization_v1beta1/test_binauthz_management_service_v1_beta1.py +++ b/packages/google-cloud-binary-authorization/tests/unit/gapic/binaryauthorization_v1beta1/test_binauthz_management_service_v1_beta1.py @@ -51,6 +51,11 @@ from google.api_core import retry as retries from google.auth import credentials as ga_credentials from google.auth.exceptions import MutualTLSChannelError +from google.iam.v1 import ( + iam_policy_pb2, # type: ignore + options_pb2, # type: ignore + policy_pb2, # type: ignore +) from google.oauth2 import service_account from google.cloud.binaryauthorization_v1beta1.services.binauthz_management_service_v1_beta1 import ( @@ -1488,6 +1493,7 @@ def test_get_policy(request_type, transport: str = "grpc"): name="name_value", description="description_value", global_policy_evaluation_mode=resources.Policy.GlobalPolicyEvaluationMode.ENABLE, + etag="etag_value", ) response = client.get_policy(request) @@ -1505,6 +1511,7 @@ def test_get_policy(request_type, transport: str = "grpc"): response.global_policy_evaluation_mode == resources.Policy.GlobalPolicyEvaluationMode.ENABLE ) + assert response.etag == "etag_value" def test_get_policy_non_empty_request_with_auto_populated_field(): @@ -1637,6 +1644,7 @@ async def test_get_policy_async(request_type, transport: str = "grpc_asyncio"): name="name_value", description="description_value", global_policy_evaluation_mode=resources.Policy.GlobalPolicyEvaluationMode.ENABLE, + etag="etag_value", ) ) response = await client.get_policy(request) @@ -1655,6 +1663,7 @@ async def test_get_policy_async(request_type, transport: str = "grpc_asyncio"): response.global_policy_evaluation_mode == resources.Policy.GlobalPolicyEvaluationMode.ENABLE ) + assert response.etag == "etag_value" def test_get_policy_field_headers(): @@ -1820,6 +1829,7 @@ def test_update_policy(request_type, transport: str = "grpc"): name="name_value", description="description_value", global_policy_evaluation_mode=resources.Policy.GlobalPolicyEvaluationMode.ENABLE, + etag="etag_value", ) response = client.update_policy(request) @@ -1837,6 +1847,7 @@ def test_update_policy(request_type, transport: str = "grpc"): response.global_policy_evaluation_mode == resources.Policy.GlobalPolicyEvaluationMode.ENABLE ) + assert response.etag == "etag_value" def test_update_policy_non_empty_request_with_auto_populated_field(): @@ -1967,6 +1978,7 @@ async def test_update_policy_async(request_type, transport: str = "grpc_asyncio" name="name_value", description="description_value", global_policy_evaluation_mode=resources.Policy.GlobalPolicyEvaluationMode.ENABLE, + etag="etag_value", ) ) response = await client.update_policy(request) @@ -1985,6 +1997,7 @@ async def test_update_policy_async(request_type, transport: str = "grpc_asyncio" response.global_policy_evaluation_mode == resources.Policy.GlobalPolicyEvaluationMode.ENABLE ) + assert response.etag == "etag_value" def test_update_policy_field_headers(): @@ -2149,6 +2162,7 @@ def test_create_attestor(request_type, transport: str = "grpc"): call.return_value = resources.Attestor( name="name_value", description="description_value", + etag="etag_value", ) response = client.create_attestor(request) @@ -2162,6 +2176,7 @@ def test_create_attestor(request_type, transport: str = "grpc"): assert isinstance(response, resources.Attestor) assert response.name == "name_value" assert response.description == "description_value" + assert response.etag == "etag_value" def test_create_attestor_non_empty_request_with_auto_populated_field(): @@ -2297,6 +2312,7 @@ async def test_create_attestor_async(request_type, transport: str = "grpc_asynci resources.Attestor( name="name_value", description="description_value", + etag="etag_value", ) ) response = await client.create_attestor(request) @@ -2311,6 +2327,7 @@ async def test_create_attestor_async(request_type, transport: str = "grpc_asynci assert isinstance(response, resources.Attestor) assert response.name == "name_value" assert response.description == "description_value" + assert response.etag == "etag_value" def test_create_attestor_field_headers(): @@ -2495,6 +2512,7 @@ def test_get_attestor(request_type, transport: str = "grpc"): call.return_value = resources.Attestor( name="name_value", description="description_value", + etag="etag_value", ) response = client.get_attestor(request) @@ -2508,6 +2526,7 @@ def test_get_attestor(request_type, transport: str = "grpc"): assert isinstance(response, resources.Attestor) assert response.name == "name_value" assert response.description == "description_value" + assert response.etag == "etag_value" def test_get_attestor_non_empty_request_with_auto_populated_field(): @@ -2641,6 +2660,7 @@ async def test_get_attestor_async(request_type, transport: str = "grpc_asyncio") resources.Attestor( name="name_value", description="description_value", + etag="etag_value", ) ) response = await client.get_attestor(request) @@ -2655,6 +2675,7 @@ async def test_get_attestor_async(request_type, transport: str = "grpc_asyncio") assert isinstance(response, resources.Attestor) assert response.name == "name_value" assert response.description == "description_value" + assert response.etag == "etag_value" def test_get_attestor_field_headers(): @@ -2819,6 +2840,7 @@ def test_update_attestor(request_type, transport: str = "grpc"): call.return_value = resources.Attestor( name="name_value", description="description_value", + etag="etag_value", ) response = client.update_attestor(request) @@ -2832,6 +2854,7 @@ def test_update_attestor(request_type, transport: str = "grpc"): assert isinstance(response, resources.Attestor) assert response.name == "name_value" assert response.description == "description_value" + assert response.etag == "etag_value" def test_update_attestor_non_empty_request_with_auto_populated_field(): @@ -2961,6 +2984,7 @@ async def test_update_attestor_async(request_type, transport: str = "grpc_asynci resources.Attestor( name="name_value", description="description_value", + etag="etag_value", ) ) response = await client.update_attestor(request) @@ -2975,6 +2999,7 @@ async def test_update_attestor_async(request_type, transport: str = "grpc_asynci assert isinstance(response, resources.Attestor) assert response.name == "name_value" assert response.description == "description_value" + assert response.etag == "etag_value" def test_update_attestor_field_headers(): @@ -5540,6 +5565,7 @@ async def test_get_policy_empty_call_grpc_asyncio(): name="name_value", description="description_value", global_policy_evaluation_mode=resources.Policy.GlobalPolicyEvaluationMode.ENABLE, + etag="etag_value", ) ) await client.get_policy(request=None) @@ -5568,6 +5594,7 @@ async def test_update_policy_empty_call_grpc_asyncio(): name="name_value", description="description_value", global_policy_evaluation_mode=resources.Policy.GlobalPolicyEvaluationMode.ENABLE, + etag="etag_value", ) ) await client.update_policy(request=None) @@ -5595,6 +5622,7 @@ async def test_create_attestor_empty_call_grpc_asyncio(): resources.Attestor( name="name_value", description="description_value", + etag="etag_value", ) ) await client.create_attestor(request=None) @@ -5622,6 +5650,7 @@ async def test_get_attestor_empty_call_grpc_asyncio(): resources.Attestor( name="name_value", description="description_value", + etag="etag_value", ) ) await client.get_attestor(request=None) @@ -5649,6 +5678,7 @@ async def test_update_attestor_empty_call_grpc_asyncio(): resources.Attestor( name="name_value", description="description_value", + etag="etag_value", ) ) await client.update_attestor(request=None) @@ -5762,6 +5792,7 @@ def test_get_policy_rest_call_success(request_type): name="name_value", description="description_value", global_policy_evaluation_mode=resources.Policy.GlobalPolicyEvaluationMode.ENABLE, + etag="etag_value", ) # Wrap the value into a proper Response obj @@ -5784,6 +5815,7 @@ def test_get_policy_rest_call_success(request_type): response.global_policy_evaluation_mode == resources.Policy.GlobalPolicyEvaluationMode.ENABLE ) + assert response.etag == "etag_value" @pytest.mark.parametrize("null_interceptor", [True, False]) @@ -5906,6 +5938,7 @@ def test_update_policy_rest_call_success(request_type): "enforcement_mode": 1, }, "update_time": {"seconds": 751, "nanos": 543}, + "etag": "etag_value", } # The version of a generated dependency at test runtime may differ from the version used during generation. # Delete any fields which are not present in the current runtime dependency @@ -5983,6 +6016,7 @@ def get_message_fields(field): name="name_value", description="description_value", global_policy_evaluation_mode=resources.Policy.GlobalPolicyEvaluationMode.ENABLE, + etag="etag_value", ) # Wrap the value into a proper Response obj @@ -6005,6 +6039,7 @@ def get_message_fields(field): response.global_policy_evaluation_mode == resources.Policy.GlobalPolicyEvaluationMode.ENABLE ) + assert response.etag == "etag_value" @pytest.mark.parametrize("null_interceptor", [True, False]) @@ -6129,6 +6164,7 @@ def test_create_attestor_rest_call_success(request_type): "delegation_service_account_email": "delegation_service_account_email_value", }, "update_time": {"seconds": 751, "nanos": 543}, + "etag": "etag_value", } # The version of a generated dependency at test runtime may differ from the version used during generation. # Delete any fields which are not present in the current runtime dependency @@ -6205,6 +6241,7 @@ def get_message_fields(field): return_value = resources.Attestor( name="name_value", description="description_value", + etag="etag_value", ) # Wrap the value into a proper Response obj @@ -6223,6 +6260,7 @@ def get_message_fields(field): assert isinstance(response, resources.Attestor) assert response.name == "name_value" assert response.description == "description_value" + assert response.etag == "etag_value" @pytest.mark.parametrize("null_interceptor", [True, False]) @@ -6336,6 +6374,7 @@ def test_get_attestor_rest_call_success(request_type): return_value = resources.Attestor( name="name_value", description="description_value", + etag="etag_value", ) # Wrap the value into a proper Response obj @@ -6354,6 +6393,7 @@ def test_get_attestor_rest_call_success(request_type): assert isinstance(response, resources.Attestor) assert response.name == "name_value" assert response.description == "description_value" + assert response.etag == "etag_value" @pytest.mark.parametrize("null_interceptor", [True, False]) @@ -6478,6 +6518,7 @@ def test_update_attestor_rest_call_success(request_type): "delegation_service_account_email": "delegation_service_account_email_value", }, "update_time": {"seconds": 751, "nanos": 543}, + "etag": "etag_value", } # The version of a generated dependency at test runtime may differ from the version used during generation. # Delete any fields which are not present in the current runtime dependency @@ -6554,6 +6595,7 @@ def get_message_fields(field): return_value = resources.Attestor( name="name_value", description="description_value", + etag="etag_value", ) # Wrap the value into a proper Response obj @@ -6572,6 +6614,7 @@ def get_message_fields(field): assert isinstance(response, resources.Attestor) assert response.name == "name_value" assert response.description == "description_value" + assert response.etag == "etag_value" @pytest.mark.parametrize("null_interceptor", [True, False]) @@ -6877,6 +6920,189 @@ def test_delete_attestor_rest_interceptors(null_interceptor): pre.assert_called_once() +def test_get_iam_policy_rest_bad_request( + request_type=iam_policy_pb2.GetIamPolicyRequest, +): + client = BinauthzManagementServiceV1Beta1Client( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict({"resource": "projects/sample1/policy"}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = Response() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.get_iam_policy(request) + + +@pytest.mark.parametrize( + "request_type", + [ + iam_policy_pb2.GetIamPolicyRequest, + dict, + ], +) +def test_get_iam_policy_rest(request_type): + client = BinauthzManagementServiceV1Beta1Client( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {"resource": "projects/sample1/policy"} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = policy_pb2.Policy() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.get_iam_policy(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, policy_pb2.Policy) + + +def test_set_iam_policy_rest_bad_request( + request_type=iam_policy_pb2.SetIamPolicyRequest, +): + client = BinauthzManagementServiceV1Beta1Client( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict({"resource": "projects/sample1/policy"}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = Response() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.set_iam_policy(request) + + +@pytest.mark.parametrize( + "request_type", + [ + iam_policy_pb2.SetIamPolicyRequest, + dict, + ], +) +def test_set_iam_policy_rest(request_type): + client = BinauthzManagementServiceV1Beta1Client( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {"resource": "projects/sample1/policy"} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = policy_pb2.Policy() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.set_iam_policy(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, policy_pb2.Policy) + + +def test_test_iam_permissions_rest_bad_request( + request_type=iam_policy_pb2.TestIamPermissionsRequest, +): + client = BinauthzManagementServiceV1Beta1Client( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict({"resource": "projects/sample1/policy"}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = Response() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.test_iam_permissions(request) + + +@pytest.mark.parametrize( + "request_type", + [ + iam_policy_pb2.TestIamPermissionsRequest, + dict, + ], +) +def test_test_iam_permissions_rest(request_type): + client = BinauthzManagementServiceV1Beta1Client( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {"resource": "projects/sample1/policy"} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = iam_policy_pb2.TestIamPermissionsResponse() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.test_iam_permissions(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, iam_policy_pb2.TestIamPermissionsResponse) + + def test_initialize_client_w_rest(): client = BinauthzManagementServiceV1Beta1Client( credentials=ga_credentials.AnonymousCredentials(), transport="rest" @@ -7057,6 +7283,9 @@ def test_binauthz_management_service_v1_beta1_base_transport(): "update_attestor", "list_attestors", "delete_attestor", + "set_iam_policy", + "get_iam_policy", + "test_iam_permissions", ) for method in methods: with pytest.raises(NotImplementedError): @@ -7664,6 +7893,625 @@ def test_client_with_default_client_info(): prep.assert_called_once_with(client_info) +def test_set_iam_policy(transport: str = "grpc"): + client = BinauthzManagementServiceV1Beta1Client( + 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 = iam_policy_pb2.SetIamPolicyRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = policy_pb2.Policy( + version=774, + etag=b"etag_blob", + ) + response = client.set_iam_policy(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, policy_pb2.Policy) + + assert response.version == 774 + + assert response.etag == b"etag_blob" + + +@pytest.mark.asyncio +async def test_set_iam_policy_async(transport: str = "grpc_asyncio"): + client = BinauthzManagementServiceV1Beta1AsyncClient( + 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 = iam_policy_pb2.SetIamPolicyRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + policy_pb2.Policy( + version=774, + etag=b"etag_blob", + ) + ) + response = await client.set_iam_policy(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, policy_pb2.Policy) + + assert response.version == 774 + + assert response.etag == b"etag_blob" + + +def test_set_iam_policy_field_headers(): + client = BinauthzManagementServiceV1Beta1Client( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = iam_policy_pb2.SetIamPolicyRequest() + request.resource = "resource/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + call.return_value = policy_pb2.Policy() + + client.set_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "resource=resource/value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_set_iam_policy_field_headers_async(): + client = BinauthzManagementServiceV1Beta1AsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = iam_policy_pb2.SetIamPolicyRequest() + request.resource = "resource/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) + + await client.set_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "resource=resource/value", + ) in kw["metadata"] + + +def test_set_iam_policy_from_dict(): + client = BinauthzManagementServiceV1Beta1Client( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = policy_pb2.Policy() + + response = client.set_iam_policy( + request={ + "resource": "resource_value", + "policy": policy_pb2.Policy(version=774), + } + ) + call.assert_called() + + +@pytest.mark.asyncio +async def test_set_iam_policy_from_dict_async(): + client = BinauthzManagementServiceV1Beta1AsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) + + response = await client.set_iam_policy( + request={ + "resource": "resource_value", + "policy": policy_pb2.Policy(version=774), + } + ) + call.assert_called() + + +def test_set_iam_policy_flattened(): + client = BinauthzManagementServiceV1Beta1Client( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = policy_pb2.Policy() + + client.set_iam_policy() + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == iam_policy_pb2.SetIamPolicyRequest() + + +@pytest.mark.asyncio +async def test_set_iam_policy_flattened_async(): + client = BinauthzManagementServiceV1Beta1AsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) + + await client.set_iam_policy() + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == iam_policy_pb2.SetIamPolicyRequest() + + +def test_get_iam_policy(transport: str = "grpc"): + client = BinauthzManagementServiceV1Beta1Client( + 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 = iam_policy_pb2.GetIamPolicyRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = policy_pb2.Policy( + version=774, + etag=b"etag_blob", + ) + + response = client.get_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, policy_pb2.Policy) + + assert response.version == 774 + + assert response.etag == b"etag_blob" + + +@pytest.mark.asyncio +async def test_get_iam_policy_async(transport: str = "grpc_asyncio"): + client = BinauthzManagementServiceV1Beta1AsyncClient( + 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 = iam_policy_pb2.GetIamPolicyRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + policy_pb2.Policy( + version=774, + etag=b"etag_blob", + ) + ) + + response = await client.get_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, policy_pb2.Policy) + + assert response.version == 774 + + assert response.etag == b"etag_blob" + + +def test_get_iam_policy_field_headers(): + client = BinauthzManagementServiceV1Beta1Client( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = iam_policy_pb2.GetIamPolicyRequest() + request.resource = "resource/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: + call.return_value = policy_pb2.Policy() + + client.get_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "resource=resource/value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_get_iam_policy_field_headers_async(): + client = BinauthzManagementServiceV1Beta1AsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = iam_policy_pb2.GetIamPolicyRequest() + request.resource = "resource/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) + + await client.get_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "resource=resource/value", + ) in kw["metadata"] + + +def test_get_iam_policy_from_dict(): + client = BinauthzManagementServiceV1Beta1Client( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = policy_pb2.Policy() + + response = client.get_iam_policy( + request={ + "resource": "resource_value", + "options": options_pb2.GetPolicyOptions(requested_policy_version=2598), + } + ) + call.assert_called() + + +@pytest.mark.asyncio +async def test_get_iam_policy_from_dict_async(): + client = BinauthzManagementServiceV1Beta1AsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) + + response = await client.get_iam_policy( + request={ + "resource": "resource_value", + "options": options_pb2.GetPolicyOptions(requested_policy_version=2598), + } + ) + call.assert_called() + + +def test_get_iam_policy_flattened(): + client = BinauthzManagementServiceV1Beta1Client( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = policy_pb2.Policy() + + client.get_iam_policy() + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == iam_policy_pb2.GetIamPolicyRequest() + + +@pytest.mark.asyncio +async def test_get_iam_policy_flattened_async(): + client = BinauthzManagementServiceV1Beta1AsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) + + await client.get_iam_policy() + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == iam_policy_pb2.GetIamPolicyRequest() + + +def test_test_iam_permissions(transport: str = "grpc"): + client = BinauthzManagementServiceV1Beta1Client( + 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 = iam_policy_pb2.TestIamPermissionsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = iam_policy_pb2.TestIamPermissionsResponse( + permissions=["permissions_value"], + ) + + response = client.test_iam_permissions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, iam_policy_pb2.TestIamPermissionsResponse) + + assert response.permissions == ["permissions_value"] + + +@pytest.mark.asyncio +async def test_test_iam_permissions_async(transport: str = "grpc_asyncio"): + client = BinauthzManagementServiceV1Beta1AsyncClient( + 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 = iam_policy_pb2.TestIamPermissionsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + iam_policy_pb2.TestIamPermissionsResponse( + permissions=["permissions_value"], + ) + ) + + response = await client.test_iam_permissions(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 response is the type that we expect. + assert isinstance(response, iam_policy_pb2.TestIamPermissionsResponse) + + assert response.permissions == ["permissions_value"] + + +def test_test_iam_permissions_field_headers(): + client = BinauthzManagementServiceV1Beta1Client( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = iam_policy_pb2.TestIamPermissionsRequest() + request.resource = "resource/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + call.return_value = iam_policy_pb2.TestIamPermissionsResponse() + + client.test_iam_permissions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "resource=resource/value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_test_iam_permissions_field_headers_async(): + client = BinauthzManagementServiceV1Beta1AsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = iam_policy_pb2.TestIamPermissionsRequest() + request.resource = "resource/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + iam_policy_pb2.TestIamPermissionsResponse() + ) + + await client.test_iam_permissions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "resource=resource/value", + ) in kw["metadata"] + + +def test_test_iam_permissions_from_dict(): + client = BinauthzManagementServiceV1Beta1Client( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = iam_policy_pb2.TestIamPermissionsResponse() + + response = client.test_iam_permissions( + request={ + "resource": "resource_value", + "permissions": ["permissions_value"], + } + ) + call.assert_called() + + +@pytest.mark.asyncio +async def test_test_iam_permissions_from_dict_async(): + client = BinauthzManagementServiceV1Beta1AsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + iam_policy_pb2.TestIamPermissionsResponse() + ) + + response = await client.test_iam_permissions( + request={ + "resource": "resource_value", + "permissions": ["permissions_value"], + } + ) + call.assert_called() + + +def test_test_iam_permissions_flattened(): + client = BinauthzManagementServiceV1Beta1Client( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = iam_policy_pb2.TestIamPermissionsResponse() + + client.test_iam_permissions() + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == iam_policy_pb2.TestIamPermissionsRequest() + + +@pytest.mark.asyncio +async def test_test_iam_permissions_flattened_async(): + client = BinauthzManagementServiceV1Beta1AsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + iam_policy_pb2.TestIamPermissionsResponse() + ) + + await client.test_iam_permissions() + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == iam_policy_pb2.TestIamPermissionsRequest() + + def test_transport_close_grpc(): client = BinauthzManagementServiceV1Beta1Client( credentials=ga_credentials.AnonymousCredentials(), transport="grpc" diff --git a/packages/google-cloud-binary-authorization/tests/unit/gapic/binaryauthorization_v1beta1/test_system_policy_v1_beta1.py b/packages/google-cloud-binary-authorization/tests/unit/gapic/binaryauthorization_v1beta1/test_system_policy_v1_beta1.py index 1dff1352d34f..550971c80454 100644 --- a/packages/google-cloud-binary-authorization/tests/unit/gapic/binaryauthorization_v1beta1/test_system_policy_v1_beta1.py +++ b/packages/google-cloud-binary-authorization/tests/unit/gapic/binaryauthorization_v1beta1/test_system_policy_v1_beta1.py @@ -51,6 +51,11 @@ from google.api_core import retry as retries from google.auth import credentials as ga_credentials from google.auth.exceptions import MutualTLSChannelError +from google.iam.v1 import ( + iam_policy_pb2, # type: ignore + options_pb2, # type: ignore + policy_pb2, # type: ignore +) from google.oauth2 import service_account from google.cloud.binaryauthorization_v1beta1.services.system_policy_v1_beta1 import ( @@ -1409,6 +1414,7 @@ def test_get_system_policy(request_type, transport: str = "grpc"): name="name_value", description="description_value", global_policy_evaluation_mode=resources.Policy.GlobalPolicyEvaluationMode.ENABLE, + etag="etag_value", ) response = client.get_system_policy(request) @@ -1426,6 +1432,7 @@ def test_get_system_policy(request_type, transport: str = "grpc"): response.global_policy_evaluation_mode == resources.Policy.GlobalPolicyEvaluationMode.ENABLE ) + assert response.etag == "etag_value" def test_get_system_policy_non_empty_request_with_auto_populated_field(): @@ -1566,6 +1573,7 @@ async def test_get_system_policy_async(request_type, transport: str = "grpc_asyn name="name_value", description="description_value", global_policy_evaluation_mode=resources.Policy.GlobalPolicyEvaluationMode.ENABLE, + etag="etag_value", ) ) response = await client.get_system_policy(request) @@ -1584,6 +1592,7 @@ async def test_get_system_policy_async(request_type, transport: str = "grpc_asyn response.global_policy_evaluation_mode == resources.Policy.GlobalPolicyEvaluationMode.ENABLE ) + assert response.etag == "etag_value" def test_get_system_policy_field_headers(): @@ -2072,6 +2081,7 @@ async def test_get_system_policy_empty_call_grpc_asyncio(): name="name_value", description="description_value", global_policy_evaluation_mode=resources.Policy.GlobalPolicyEvaluationMode.ENABLE, + etag="etag_value", ) ) await client.get_system_policy(request=None) @@ -2139,6 +2149,7 @@ def test_get_system_policy_rest_call_success(request_type): name="name_value", description="description_value", global_policy_evaluation_mode=resources.Policy.GlobalPolicyEvaluationMode.ENABLE, + etag="etag_value", ) # Wrap the value into a proper Response obj @@ -2161,6 +2172,7 @@ def test_get_system_policy_rest_call_success(request_type): response.global_policy_evaluation_mode == resources.Policy.GlobalPolicyEvaluationMode.ENABLE ) + assert response.etag == "etag_value" @pytest.mark.parametrize("null_interceptor", [True, False]) @@ -2226,6 +2238,189 @@ def test_get_system_policy_rest_interceptors(null_interceptor): post_with_metadata.assert_called_once() +def test_get_iam_policy_rest_bad_request( + request_type=iam_policy_pb2.GetIamPolicyRequest, +): + client = SystemPolicyV1Beta1Client( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict({"resource": "projects/sample1/policy"}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = Response() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.get_iam_policy(request) + + +@pytest.mark.parametrize( + "request_type", + [ + iam_policy_pb2.GetIamPolicyRequest, + dict, + ], +) +def test_get_iam_policy_rest(request_type): + client = SystemPolicyV1Beta1Client( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {"resource": "projects/sample1/policy"} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = policy_pb2.Policy() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.get_iam_policy(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, policy_pb2.Policy) + + +def test_set_iam_policy_rest_bad_request( + request_type=iam_policy_pb2.SetIamPolicyRequest, +): + client = SystemPolicyV1Beta1Client( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict({"resource": "projects/sample1/policy"}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = Response() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.set_iam_policy(request) + + +@pytest.mark.parametrize( + "request_type", + [ + iam_policy_pb2.SetIamPolicyRequest, + dict, + ], +) +def test_set_iam_policy_rest(request_type): + client = SystemPolicyV1Beta1Client( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {"resource": "projects/sample1/policy"} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = policy_pb2.Policy() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.set_iam_policy(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, policy_pb2.Policy) + + +def test_test_iam_permissions_rest_bad_request( + request_type=iam_policy_pb2.TestIamPermissionsRequest, +): + client = SystemPolicyV1Beta1Client( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict({"resource": "projects/sample1/policy"}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = Response() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.test_iam_permissions(request) + + +@pytest.mark.parametrize( + "request_type", + [ + iam_policy_pb2.TestIamPermissionsRequest, + dict, + ], +) +def test_test_iam_permissions_rest(request_type): + client = SystemPolicyV1Beta1Client( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {"resource": "projects/sample1/policy"} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = iam_policy_pb2.TestIamPermissionsResponse() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.test_iam_permissions(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, iam_policy_pb2.TestIamPermissionsResponse) + + def test_initialize_client_w_rest(): client = SystemPolicyV1Beta1Client( credentials=ga_credentials.AnonymousCredentials(), transport="rest" @@ -2286,7 +2481,12 @@ def test_system_policy_v1_beta1_base_transport(): # Every method on the transport should just blindly # raise NotImplementedError. - methods = ("get_system_policy",) + methods = ( + "get_system_policy", + "set_iam_policy", + "get_iam_policy", + "test_iam_permissions", + ) for method in methods: with pytest.raises(NotImplementedError): getattr(transport, method)(request=object()) @@ -2831,6 +3031,625 @@ def test_client_with_default_client_info(): prep.assert_called_once_with(client_info) +def test_set_iam_policy(transport: str = "grpc"): + client = SystemPolicyV1Beta1Client( + 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 = iam_policy_pb2.SetIamPolicyRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = policy_pb2.Policy( + version=774, + etag=b"etag_blob", + ) + response = client.set_iam_policy(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, policy_pb2.Policy) + + assert response.version == 774 + + assert response.etag == b"etag_blob" + + +@pytest.mark.asyncio +async def test_set_iam_policy_async(transport: str = "grpc_asyncio"): + client = SystemPolicyV1Beta1AsyncClient( + 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 = iam_policy_pb2.SetIamPolicyRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + policy_pb2.Policy( + version=774, + etag=b"etag_blob", + ) + ) + response = await client.set_iam_policy(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, policy_pb2.Policy) + + assert response.version == 774 + + assert response.etag == b"etag_blob" + + +def test_set_iam_policy_field_headers(): + client = SystemPolicyV1Beta1Client( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = iam_policy_pb2.SetIamPolicyRequest() + request.resource = "resource/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + call.return_value = policy_pb2.Policy() + + client.set_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "resource=resource/value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_set_iam_policy_field_headers_async(): + client = SystemPolicyV1Beta1AsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = iam_policy_pb2.SetIamPolicyRequest() + request.resource = "resource/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) + + await client.set_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "resource=resource/value", + ) in kw["metadata"] + + +def test_set_iam_policy_from_dict(): + client = SystemPolicyV1Beta1Client( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = policy_pb2.Policy() + + response = client.set_iam_policy( + request={ + "resource": "resource_value", + "policy": policy_pb2.Policy(version=774), + } + ) + call.assert_called() + + +@pytest.mark.asyncio +async def test_set_iam_policy_from_dict_async(): + client = SystemPolicyV1Beta1AsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) + + response = await client.set_iam_policy( + request={ + "resource": "resource_value", + "policy": policy_pb2.Policy(version=774), + } + ) + call.assert_called() + + +def test_set_iam_policy_flattened(): + client = SystemPolicyV1Beta1Client( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = policy_pb2.Policy() + + client.set_iam_policy() + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == iam_policy_pb2.SetIamPolicyRequest() + + +@pytest.mark.asyncio +async def test_set_iam_policy_flattened_async(): + client = SystemPolicyV1Beta1AsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) + + await client.set_iam_policy() + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == iam_policy_pb2.SetIamPolicyRequest() + + +def test_get_iam_policy(transport: str = "grpc"): + client = SystemPolicyV1Beta1Client( + 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 = iam_policy_pb2.GetIamPolicyRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = policy_pb2.Policy( + version=774, + etag=b"etag_blob", + ) + + response = client.get_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, policy_pb2.Policy) + + assert response.version == 774 + + assert response.etag == b"etag_blob" + + +@pytest.mark.asyncio +async def test_get_iam_policy_async(transport: str = "grpc_asyncio"): + client = SystemPolicyV1Beta1AsyncClient( + 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 = iam_policy_pb2.GetIamPolicyRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + policy_pb2.Policy( + version=774, + etag=b"etag_blob", + ) + ) + + response = await client.get_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, policy_pb2.Policy) + + assert response.version == 774 + + assert response.etag == b"etag_blob" + + +def test_get_iam_policy_field_headers(): + client = SystemPolicyV1Beta1Client( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = iam_policy_pb2.GetIamPolicyRequest() + request.resource = "resource/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: + call.return_value = policy_pb2.Policy() + + client.get_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "resource=resource/value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_get_iam_policy_field_headers_async(): + client = SystemPolicyV1Beta1AsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = iam_policy_pb2.GetIamPolicyRequest() + request.resource = "resource/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) + + await client.get_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "resource=resource/value", + ) in kw["metadata"] + + +def test_get_iam_policy_from_dict(): + client = SystemPolicyV1Beta1Client( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = policy_pb2.Policy() + + response = client.get_iam_policy( + request={ + "resource": "resource_value", + "options": options_pb2.GetPolicyOptions(requested_policy_version=2598), + } + ) + call.assert_called() + + +@pytest.mark.asyncio +async def test_get_iam_policy_from_dict_async(): + client = SystemPolicyV1Beta1AsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) + + response = await client.get_iam_policy( + request={ + "resource": "resource_value", + "options": options_pb2.GetPolicyOptions(requested_policy_version=2598), + } + ) + call.assert_called() + + +def test_get_iam_policy_flattened(): + client = SystemPolicyV1Beta1Client( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = policy_pb2.Policy() + + client.get_iam_policy() + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == iam_policy_pb2.GetIamPolicyRequest() + + +@pytest.mark.asyncio +async def test_get_iam_policy_flattened_async(): + client = SystemPolicyV1Beta1AsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) + + await client.get_iam_policy() + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == iam_policy_pb2.GetIamPolicyRequest() + + +def test_test_iam_permissions(transport: str = "grpc"): + client = SystemPolicyV1Beta1Client( + 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 = iam_policy_pb2.TestIamPermissionsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = iam_policy_pb2.TestIamPermissionsResponse( + permissions=["permissions_value"], + ) + + response = client.test_iam_permissions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, iam_policy_pb2.TestIamPermissionsResponse) + + assert response.permissions == ["permissions_value"] + + +@pytest.mark.asyncio +async def test_test_iam_permissions_async(transport: str = "grpc_asyncio"): + client = SystemPolicyV1Beta1AsyncClient( + 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 = iam_policy_pb2.TestIamPermissionsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + iam_policy_pb2.TestIamPermissionsResponse( + permissions=["permissions_value"], + ) + ) + + response = await client.test_iam_permissions(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 response is the type that we expect. + assert isinstance(response, iam_policy_pb2.TestIamPermissionsResponse) + + assert response.permissions == ["permissions_value"] + + +def test_test_iam_permissions_field_headers(): + client = SystemPolicyV1Beta1Client( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = iam_policy_pb2.TestIamPermissionsRequest() + request.resource = "resource/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + call.return_value = iam_policy_pb2.TestIamPermissionsResponse() + + client.test_iam_permissions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "resource=resource/value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_test_iam_permissions_field_headers_async(): + client = SystemPolicyV1Beta1AsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = iam_policy_pb2.TestIamPermissionsRequest() + request.resource = "resource/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + iam_policy_pb2.TestIamPermissionsResponse() + ) + + await client.test_iam_permissions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "resource=resource/value", + ) in kw["metadata"] + + +def test_test_iam_permissions_from_dict(): + client = SystemPolicyV1Beta1Client( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = iam_policy_pb2.TestIamPermissionsResponse() + + response = client.test_iam_permissions( + request={ + "resource": "resource_value", + "permissions": ["permissions_value"], + } + ) + call.assert_called() + + +@pytest.mark.asyncio +async def test_test_iam_permissions_from_dict_async(): + client = SystemPolicyV1Beta1AsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + iam_policy_pb2.TestIamPermissionsResponse() + ) + + response = await client.test_iam_permissions( + request={ + "resource": "resource_value", + "permissions": ["permissions_value"], + } + ) + call.assert_called() + + +def test_test_iam_permissions_flattened(): + client = SystemPolicyV1Beta1Client( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = iam_policy_pb2.TestIamPermissionsResponse() + + client.test_iam_permissions() + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == iam_policy_pb2.TestIamPermissionsRequest() + + +@pytest.mark.asyncio +async def test_test_iam_permissions_flattened_async(): + client = SystemPolicyV1Beta1AsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + iam_policy_pb2.TestIamPermissionsResponse() + ) + + await client.test_iam_permissions() + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == iam_policy_pb2.TestIamPermissionsRequest() + + def test_transport_close_grpc(): client = SystemPolicyV1Beta1Client( credentials=ga_credentials.AnonymousCredentials(), transport="grpc" diff --git a/packages/google-cloud-memorystore/google/cloud/memorystore/__init__.py b/packages/google-cloud-memorystore/google/cloud/memorystore/__init__.py index 178a77365fea..ea0114a7f7bb 100644 --- a/packages/google-cloud-memorystore/google/cloud/memorystore/__init__.py +++ b/packages/google-cloud-memorystore/google/cloud/memorystore/__init__.py @@ -37,6 +37,7 @@ DiscoveryEndpoint, EncryptionInfo, ExportBackupRequest, + FinishMigrationRequest, GetBackupCollectionRequest, GetBackupRequest, GetCertificateAuthorityRequest, @@ -51,6 +52,7 @@ ListInstancesResponse, MaintenancePolicy, MaintenanceSchedule, + MigrationConfig, NodeConfig, OperationMetadata, PersistenceConfig, @@ -59,7 +61,9 @@ PscConnection, PscConnectionStatus, RescheduleMaintenanceRequest, + SelfManagedSource, SharedRegionalCertificateAuthority, + StartMigrationRequest, UpdateInstanceRequest, WeeklyMaintenanceWindow, ZoneDistributionConfig, @@ -81,6 +85,7 @@ "DiscoveryEndpoint", "EncryptionInfo", "ExportBackupRequest", + "FinishMigrationRequest", "GetBackupCollectionRequest", "GetBackupRequest", "GetCertificateAuthorityRequest", @@ -95,6 +100,7 @@ "ListInstancesResponse", "MaintenancePolicy", "MaintenanceSchedule", + "MigrationConfig", "NodeConfig", "OperationMetadata", "PersistenceConfig", @@ -102,7 +108,9 @@ "PscAutoConnection", "PscConnection", "RescheduleMaintenanceRequest", + "SelfManagedSource", "SharedRegionalCertificateAuthority", + "StartMigrationRequest", "UpdateInstanceRequest", "WeeklyMaintenanceWindow", "ZoneDistributionConfig", diff --git a/packages/google-cloud-memorystore/google/cloud/memorystore_v1/__init__.py b/packages/google-cloud-memorystore/google/cloud/memorystore_v1/__init__.py index fd0f4561b3f1..2c754396b1d6 100644 --- a/packages/google-cloud-memorystore/google/cloud/memorystore_v1/__init__.py +++ b/packages/google-cloud-memorystore/google/cloud/memorystore_v1/__init__.py @@ -39,6 +39,7 @@ DiscoveryEndpoint, EncryptionInfo, ExportBackupRequest, + FinishMigrationRequest, GetBackupCollectionRequest, GetBackupRequest, GetCertificateAuthorityRequest, @@ -53,6 +54,7 @@ ListInstancesResponse, MaintenancePolicy, MaintenanceSchedule, + MigrationConfig, NodeConfig, OperationMetadata, PersistenceConfig, @@ -61,7 +63,9 @@ PscConnection, PscConnectionStatus, RescheduleMaintenanceRequest, + SelfManagedSource, SharedRegionalCertificateAuthority, + StartMigrationRequest, UpdateInstanceRequest, WeeklyMaintenanceWindow, ZoneDistributionConfig, @@ -166,6 +170,7 @@ def _get_version(dependency_name): "DiscoveryEndpoint", "EncryptionInfo", "ExportBackupRequest", + "FinishMigrationRequest", "GetBackupCollectionRequest", "GetBackupRequest", "GetCertificateAuthorityRequest", @@ -181,6 +186,7 @@ def _get_version(dependency_name): "MaintenancePolicy", "MaintenanceSchedule", "MemorystoreClient", + "MigrationConfig", "NodeConfig", "OperationMetadata", "PersistenceConfig", @@ -189,7 +195,9 @@ def _get_version(dependency_name): "PscConnection", "PscConnectionStatus", "RescheduleMaintenanceRequest", + "SelfManagedSource", "SharedRegionalCertificateAuthority", + "StartMigrationRequest", "UpdateInstanceRequest", "WeeklyMaintenanceWindow", "ZoneDistributionConfig", diff --git a/packages/google-cloud-memorystore/google/cloud/memorystore_v1/gapic_metadata.json b/packages/google-cloud-memorystore/google/cloud/memorystore_v1/gapic_metadata.json index 5f712fecdeab..766b2d235c3f 100644 --- a/packages/google-cloud-memorystore/google/cloud/memorystore_v1/gapic_metadata.json +++ b/packages/google-cloud-memorystore/google/cloud/memorystore_v1/gapic_metadata.json @@ -35,6 +35,11 @@ "export_backup" ] }, + "FinishMigration": { + "methods": [ + "finish_migration" + ] + }, "GetBackup": { "methods": [ "get_backup" @@ -80,6 +85,11 @@ "reschedule_maintenance" ] }, + "StartMigration": { + "methods": [ + "start_migration" + ] + }, "UpdateInstance": { "methods": [ "update_instance" @@ -115,6 +125,11 @@ "export_backup" ] }, + "FinishMigration": { + "methods": [ + "finish_migration" + ] + }, "GetBackup": { "methods": [ "get_backup" @@ -160,6 +175,11 @@ "reschedule_maintenance" ] }, + "StartMigration": { + "methods": [ + "start_migration" + ] + }, "UpdateInstance": { "methods": [ "update_instance" @@ -195,6 +215,11 @@ "export_backup" ] }, + "FinishMigration": { + "methods": [ + "finish_migration" + ] + }, "GetBackup": { "methods": [ "get_backup" @@ -240,6 +265,11 @@ "reschedule_maintenance" ] }, + "StartMigration": { + "methods": [ + "start_migration" + ] + }, "UpdateInstance": { "methods": [ "update_instance" diff --git a/packages/google-cloud-memorystore/google/cloud/memorystore_v1/services/memorystore/async_client.py b/packages/google-cloud-memorystore/google/cloud/memorystore_v1/services/memorystore/async_client.py index 501e8920a860..8c4223b24c39 100644 --- a/packages/google-cloud-memorystore/google/cloud/memorystore_v1/services/memorystore/async_client.py +++ b/packages/google-cloud-memorystore/google/cloud/memorystore_v1/services/memorystore/async_client.py @@ -109,6 +109,10 @@ class MemorystoreAsyncClient: parse_instance_path = staticmethod(MemorystoreClient.parse_instance_path) network_path = staticmethod(MemorystoreClient.network_path) parse_network_path = staticmethod(MemorystoreClient.parse_network_path) + network_attachment_path = staticmethod(MemorystoreClient.network_attachment_path) + parse_network_attachment_path = staticmethod( + MemorystoreClient.parse_network_attachment_path + ) service_attachment_path = staticmethod(MemorystoreClient.service_attachment_path) parse_service_attachment_path = staticmethod( MemorystoreClient.parse_service_attachment_path @@ -392,7 +396,7 @@ async def sample_list_instances(): Returns: google.cloud.memorystore_v1.services.memorystore.pagers.ListInstancesAsyncPager: - Response message for [ListInstances][]. + Response message for ListInstances. Iterating over this object will yield results and resolve additional pages automatically. @@ -1033,7 +1037,7 @@ async def sample_get_certificate_authority(): Args: request (Optional[Union[google.cloud.memorystore_v1.types.GetCertificateAuthorityRequest, dict]]): - The request object. Request message for [GetCertificateAuthority][]. + The request object. Request message for ``GetCertificateAuthority``. name (:class:`str`): Required. The name of the certificate authority. Format: @@ -1148,8 +1152,7 @@ async def sample_get_shared_regional_certificate_authority(): Args: request (Optional[Union[google.cloud.memorystore_v1.types.GetSharedRegionalCertificateAuthorityRequest, dict]]): - The request object. Request for - [GetSharedRegionalCertificateAuthority][google.cloud.memorystore.v1.Memorystore.GetSharedRegionalCertificateAuthority]. + The request object. Request for ``GetSharedRegionalCertificateAuthority``. name (:class:`str`): Required. Regional certificate authority resource name using the form: @@ -1420,7 +1423,7 @@ async def sample_list_backup_collections(): Args: request (Optional[Union[google.cloud.memorystore_v1.types.ListBackupCollectionsRequest, dict]]): - The request object. Request for [ListBackupCollections] + The request object. Request for ``ListBackupCollections``. parent (:class:`str`): Required. The resource name of the backupCollection location using the form: @@ -1440,7 +1443,7 @@ async def sample_list_backup_collections(): Returns: google.cloud.memorystore_v1.services.memorystore.pagers.ListBackupCollectionsAsyncPager: - Response for [ListBackupCollections]. + Response for ListBackupCollections. Iterating over this object will yield results and resolve additional pages automatically. @@ -1545,7 +1548,7 @@ async def sample_get_backup_collection(): Args: request (Optional[Union[google.cloud.memorystore_v1.types.GetBackupCollectionRequest, dict]]): - The request object. Request for [GetBackupCollection]. + The request object. Request for ``GetBackupCollection``. name (:class:`str`): Required. Instance backupCollection resource name using the form: @@ -1656,7 +1659,7 @@ async def sample_list_backups(): Args: request (Optional[Union[google.cloud.memorystore_v1.types.ListBackupsRequest, dict]]): - The request object. Request for [ListBackups]. + The request object. Request for ``ListBackups``. parent (:class:`str`): Required. The resource name of the backupCollection using the form: @@ -1675,7 +1678,7 @@ async def sample_list_backups(): Returns: google.cloud.memorystore_v1.services.memorystore.pagers.ListBackupsAsyncPager: - Response for [ListBackups]. + Response for ListBackups. Iterating over this object will yield results and resolve additional pages automatically. @@ -1780,7 +1783,7 @@ async def sample_get_backup(): Args: request (Optional[Union[google.cloud.memorystore_v1.types.GetBackupRequest, dict]]): - The request object. Request for [GetBackup]. + The request object. Request for ``GetBackup``. name (:class:`str`): Required. Instance backup resource name using the form: ``projects/{project_id}/locations/{location_id}/backupCollections/{backup_collection_id}/backups/{backup_id}`` @@ -1892,7 +1895,7 @@ async def sample_delete_backup(): Args: request (Optional[Union[google.cloud.memorystore_v1.types.DeleteBackupRequest, dict]]): - The request object. Request for [DeleteBackup]. + The request object. Request for ``DeleteBackup``. name (:class:`str`): Required. Instance backup resource name using the form: ``projects/{project_id}/locations/{location_id}/backupCollections/{backup_collection_id}/backups/{backup_id}`` @@ -2025,7 +2028,7 @@ async def sample_export_backup(): Args: request (Optional[Union[google.cloud.memorystore_v1.types.ExportBackupRequest, dict]]): - The request object. Request for [ExportBackup]. + The request object. Request for ``ExportBackup``. retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -2141,7 +2144,7 @@ async def sample_backup_instance(): Args: request (Optional[Union[google.cloud.memorystore_v1.types.BackupInstanceRequest, dict]]): - The request object. Request for [BackupInstance]. + The request object. Request for ``BackupInstance``. name (:class:`str`): Required. Instance resource name using the form: ``projects/{project_id}/locations/{location_id}/instances/{instance_id}`` @@ -2224,6 +2227,265 @@ async def sample_backup_instance(): # Done; return the response. return response + async def start_migration( + self, + request: Optional[Union[memorystore.StartMigrationRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation_async.AsyncOperation: + r"""Initiates the migration of a source instance to the + target Memorystore instance. + + After the successful completion of this operation, the + target instance will: + + 1. Set up replication with the source instance and + replicate any writes to the source instance. + 2. Only allow reads. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import memorystore_v1 + + async def sample_start_migration(): + # Create a client + client = memorystore_v1.MemorystoreAsyncClient() + + # Initialize request argument(s) + self_managed_source = memorystore_v1.SelfManagedSource() + self_managed_source.ip_address = "ip_address_value" + self_managed_source.port = 453 + self_managed_source.network_attachment = "network_attachment_value" + + request = memorystore_v1.StartMigrationRequest( + self_managed_source=self_managed_source, + name="name_value", + ) + + # Make the request + operation = await client.start_migration(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.memorystore_v1.types.StartMigrationRequest, dict]]): + The request object. Request for ``StartMigration``. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.memorystore_v1.types.Instance` A + Memorystore instance. + + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, memorystore.StartMigrationRequest): + request = memorystore.StartMigrationRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.start_migration + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + memorystore.Instance, + metadata_type=memorystore.OperationMetadata, + ) + + # Done; return the response. + return response + + async def finish_migration( + self, + request: Optional[Union[memorystore.FinishMigrationRequest, dict]] = None, + *, + name: Optional[str] = None, + force: Optional[bool] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation_async.AsyncOperation: + r"""Finalizes the migration process. + + After the successful completion of this operation, the + target instance will: + + 1. Stop replicating from the source instance. + 2. Allow both reads and writes. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import memorystore_v1 + + async def sample_finish_migration(): + # Create a client + client = memorystore_v1.MemorystoreAsyncClient() + + # Initialize request argument(s) + request = memorystore_v1.FinishMigrationRequest( + name="name_value", + ) + + # Make the request + operation = await client.finish_migration(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.memorystore_v1.types.FinishMigrationRequest, dict]]): + The request object. Request for ``FinishMigration``. + name (:class:`str`): + Required. The resource name of the + instance to finalize migration on. + Format: + projects/{project}/locations/{location}/instances/{instance} + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + force (:class:`bool`): + Optional. By default, the ``FinishMigration`` operation + ensures the target replication offset to catch up to the + source offset as of the time of the call. Set this field + to ``true`` to bypass this offset verification check. + + This corresponds to the ``force`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.memorystore_v1.types.Instance` A + Memorystore instance. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name, force] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, memorystore.FinishMigrationRequest): + request = memorystore.FinishMigrationRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + if force is not None: + request.force = force + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.finish_migration + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + memorystore.Instance, + metadata_type=memorystore.OperationMetadata, + ) + + # Done; return the response. + return response + async def list_operations( self, request: Optional[Union[operations_pb2.ListOperationsRequest, dict]] = None, diff --git a/packages/google-cloud-memorystore/google/cloud/memorystore_v1/services/memorystore/client.py b/packages/google-cloud-memorystore/google/cloud/memorystore_v1/services/memorystore/client.py index 7c2b01c91f6f..0f8e750c1ac0 100644 --- a/packages/google-cloud-memorystore/google/cloud/memorystore_v1/services/memorystore/client.py +++ b/packages/google-cloud-memorystore/google/cloud/memorystore_v1/services/memorystore/client.py @@ -437,6 +437,28 @@ def parse_network_path(path: str) -> Dict[str, str]: ) return m.groupdict() if m else {} + @staticmethod + def network_attachment_path( + project: str, + region: str, + network_attachment: str, + ) -> str: + """Returns a fully-qualified network_attachment string.""" + return "projects/{project}/regions/{region}/networkAttachments/{network_attachment}".format( + project=project, + region=region, + network_attachment=network_attachment, + ) + + @staticmethod + def parse_network_attachment_path(path: str) -> Dict[str, str]: + """Parses a network_attachment path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/regions/(?P.+?)/networkAttachments/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + @staticmethod def service_attachment_path( project: str, @@ -1014,7 +1036,7 @@ def sample_list_instances(): Returns: google.cloud.memorystore_v1.services.memorystore.pagers.ListInstancesPager: - Response message for [ListInstances][]. + Response message for ListInstances. Iterating over this object will yield results and resolve additional pages automatically. @@ -1640,7 +1662,7 @@ def sample_get_certificate_authority(): Args: request (Union[google.cloud.memorystore_v1.types.GetCertificateAuthorityRequest, dict]): - The request object. Request message for [GetCertificateAuthority][]. + The request object. Request message for ``GetCertificateAuthority``. name (str): Required. The name of the certificate authority. Format: @@ -1754,8 +1776,7 @@ def sample_get_shared_regional_certificate_authority(): Args: request (Union[google.cloud.memorystore_v1.types.GetSharedRegionalCertificateAuthorityRequest, dict]): - The request object. Request for - [GetSharedRegionalCertificateAuthority][google.cloud.memorystore.v1.Memorystore.GetSharedRegionalCertificateAuthority]. + The request object. Request for ``GetSharedRegionalCertificateAuthority``. name (str): Required. Regional certificate authority resource name using the form: @@ -2022,7 +2043,7 @@ def sample_list_backup_collections(): Args: request (Union[google.cloud.memorystore_v1.types.ListBackupCollectionsRequest, dict]): - The request object. Request for [ListBackupCollections] + The request object. Request for ``ListBackupCollections``. parent (str): Required. The resource name of the backupCollection location using the form: @@ -2042,7 +2063,7 @@ def sample_list_backup_collections(): Returns: google.cloud.memorystore_v1.services.memorystore.pagers.ListBackupCollectionsPager: - Response for [ListBackupCollections]. + Response for ListBackupCollections. Iterating over this object will yield results and resolve additional pages automatically. @@ -2144,7 +2165,7 @@ def sample_get_backup_collection(): Args: request (Union[google.cloud.memorystore_v1.types.GetBackupCollectionRequest, dict]): - The request object. Request for [GetBackupCollection]. + The request object. Request for ``GetBackupCollection``. name (str): Required. Instance backupCollection resource name using the form: @@ -2252,7 +2273,7 @@ def sample_list_backups(): Args: request (Union[google.cloud.memorystore_v1.types.ListBackupsRequest, dict]): - The request object. Request for [ListBackups]. + The request object. Request for ``ListBackups``. parent (str): Required. The resource name of the backupCollection using the form: @@ -2271,7 +2292,7 @@ def sample_list_backups(): Returns: google.cloud.memorystore_v1.services.memorystore.pagers.ListBackupsPager: - Response for [ListBackups]. + Response for ListBackups. Iterating over this object will yield results and resolve additional pages automatically. @@ -2373,7 +2394,7 @@ def sample_get_backup(): Args: request (Union[google.cloud.memorystore_v1.types.GetBackupRequest, dict]): - The request object. Request for [GetBackup]. + The request object. Request for ``GetBackup``. name (str): Required. Instance backup resource name using the form: ``projects/{project_id}/locations/{location_id}/backupCollections/{backup_collection_id}/backups/{backup_id}`` @@ -2482,7 +2503,7 @@ def sample_delete_backup(): Args: request (Union[google.cloud.memorystore_v1.types.DeleteBackupRequest, dict]): - The request object. Request for [DeleteBackup]. + The request object. Request for ``DeleteBackup``. name (str): Required. Instance backup resource name using the form: ``projects/{project_id}/locations/{location_id}/backupCollections/{backup_collection_id}/backups/{backup_id}`` @@ -2612,7 +2633,7 @@ def sample_export_backup(): Args: request (Union[google.cloud.memorystore_v1.types.ExportBackupRequest, dict]): - The request object. Request for [ExportBackup]. + The request object. Request for ``ExportBackup``. retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -2726,7 +2747,7 @@ def sample_backup_instance(): Args: request (Union[google.cloud.memorystore_v1.types.BackupInstanceRequest, dict]): - The request object. Request for [BackupInstance]. + The request object. Request for ``BackupInstance``. name (str): Required. Instance resource name using the form: ``projects/{project_id}/locations/{location_id}/instances/{instance_id}`` @@ -2806,6 +2827,260 @@ def sample_backup_instance(): # Done; return the response. return response + def start_migration( + self, + request: Optional[Union[memorystore.StartMigrationRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: + r"""Initiates the migration of a source instance to the + target Memorystore instance. + + After the successful completion of this operation, the + target instance will: + + 1. Set up replication with the source instance and + replicate any writes to the source instance. + 2. Only allow reads. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import memorystore_v1 + + def sample_start_migration(): + # Create a client + client = memorystore_v1.MemorystoreClient() + + # Initialize request argument(s) + self_managed_source = memorystore_v1.SelfManagedSource() + self_managed_source.ip_address = "ip_address_value" + self_managed_source.port = 453 + self_managed_source.network_attachment = "network_attachment_value" + + request = memorystore_v1.StartMigrationRequest( + self_managed_source=self_managed_source, + name="name_value", + ) + + # Make the request + operation = client.start_migration(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.memorystore_v1.types.StartMigrationRequest, dict]): + The request object. Request for ``StartMigration``. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.memorystore_v1.types.Instance` A + Memorystore instance. + + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, memorystore.StartMigrationRequest): + request = memorystore.StartMigrationRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.start_migration] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + memorystore.Instance, + metadata_type=memorystore.OperationMetadata, + ) + + # Done; return the response. + return response + + def finish_migration( + self, + request: Optional[Union[memorystore.FinishMigrationRequest, dict]] = None, + *, + name: Optional[str] = None, + force: Optional[bool] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: + r"""Finalizes the migration process. + + After the successful completion of this operation, the + target instance will: + + 1. Stop replicating from the source instance. + 2. Allow both reads and writes. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import memorystore_v1 + + def sample_finish_migration(): + # Create a client + client = memorystore_v1.MemorystoreClient() + + # Initialize request argument(s) + request = memorystore_v1.FinishMigrationRequest( + name="name_value", + ) + + # Make the request + operation = client.finish_migration(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.memorystore_v1.types.FinishMigrationRequest, dict]): + The request object. Request for ``FinishMigration``. + name (str): + Required. The resource name of the + instance to finalize migration on. + Format: + projects/{project}/locations/{location}/instances/{instance} + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + force (bool): + Optional. By default, the ``FinishMigration`` operation + ensures the target replication offset to catch up to the + source offset as of the time of the call. Set this field + to ``true`` to bypass this offset verification check. + + This corresponds to the ``force`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.memorystore_v1.types.Instance` A + Memorystore instance. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name, force] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, memorystore.FinishMigrationRequest): + request = memorystore.FinishMigrationRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + if force is not None: + request.force = force + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.finish_migration] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + memorystore.Instance, + metadata_type=memorystore.OperationMetadata, + ) + + # Done; return the response. + return response + def __enter__(self) -> "MemorystoreClient": return self diff --git a/packages/google-cloud-memorystore/google/cloud/memorystore_v1/services/memorystore/transports/base.py b/packages/google-cloud-memorystore/google/cloud/memorystore_v1/services/memorystore/transports/base.py index f12d13ed397d..022df72377ab 100644 --- a/packages/google-cloud-memorystore/google/cloud/memorystore_v1/services/memorystore/transports/base.py +++ b/packages/google-cloud-memorystore/google/cloud/memorystore_v1/services/memorystore/transports/base.py @@ -41,7 +41,11 @@ class MemorystoreTransport(abc.ABC): """Abstract transport class for Memorystore.""" - AUTH_SCOPES = ("https://www.googleapis.com/auth/cloud-platform",) + AUTH_SCOPES = ( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/memorystore.read-only", + "https://www.googleapis.com/auth/memorystore.read-write", + ) DEFAULT_HOST: str = "memorystore.googleapis.com" @@ -246,6 +250,16 @@ def _prep_wrapped_messages(self, client_info): default_timeout=None, client_info=client_info, ), + self.start_migration: gapic_v1.method.wrap_method( + self.start_migration, + default_timeout=None, + client_info=client_info, + ), + self.finish_migration: gapic_v1.method.wrap_method( + self.finish_migration, + default_timeout=None, + client_info=client_info, + ), self.get_location: gapic_v1.method.wrap_method( self.get_location, default_timeout=None, @@ -441,6 +455,24 @@ def backup_instance( ]: raise NotImplementedError() + @property + def start_migration( + self, + ) -> Callable[ + [memorystore.StartMigrationRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + + @property + def finish_migration( + self, + ) -> Callable[ + [memorystore.FinishMigrationRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + @property def list_operations( self, diff --git a/packages/google-cloud-memorystore/google/cloud/memorystore_v1/services/memorystore/transports/grpc.py b/packages/google-cloud-memorystore/google/cloud/memorystore_v1/services/memorystore/transports/grpc.py index 67118babd9be..f13ac98ba47e 100644 --- a/packages/google-cloud-memorystore/google/cloud/memorystore_v1/services/memorystore/transports/grpc.py +++ b/packages/google-cloud-memorystore/google/cloud/memorystore_v1/services/memorystore/transports/grpc.py @@ -773,6 +773,72 @@ def backup_instance( ) return self._stubs["backup_instance"] + @property + def start_migration( + self, + ) -> Callable[[memorystore.StartMigrationRequest], operations_pb2.Operation]: + r"""Return a callable for the start migration method over gRPC. + + Initiates the migration of a source instance to the + target Memorystore instance. + + After the successful completion of this operation, the + target instance will: + + 1. Set up replication with the source instance and + replicate any writes to the source instance. + 2. Only allow reads. + + Returns: + Callable[[~.StartMigrationRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "start_migration" not in self._stubs: + self._stubs["start_migration"] = self._logged_channel.unary_unary( + "/google.cloud.memorystore.v1.Memorystore/StartMigration", + request_serializer=memorystore.StartMigrationRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["start_migration"] + + @property + def finish_migration( + self, + ) -> Callable[[memorystore.FinishMigrationRequest], operations_pb2.Operation]: + r"""Return a callable for the finish migration method over gRPC. + + Finalizes the migration process. + + After the successful completion of this operation, the + target instance will: + + 1. Stop replicating from the source instance. + 2. Allow both reads and writes. + + Returns: + Callable[[~.FinishMigrationRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "finish_migration" not in self._stubs: + self._stubs["finish_migration"] = self._logged_channel.unary_unary( + "/google.cloud.memorystore.v1.Memorystore/FinishMigration", + request_serializer=memorystore.FinishMigrationRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["finish_migration"] + def close(self): self._logged_channel.close() diff --git a/packages/google-cloud-memorystore/google/cloud/memorystore_v1/services/memorystore/transports/grpc_asyncio.py b/packages/google-cloud-memorystore/google/cloud/memorystore_v1/services/memorystore/transports/grpc_asyncio.py index d4ecd7dc2f10..c3f73ca34185 100644 --- a/packages/google-cloud-memorystore/google/cloud/memorystore_v1/services/memorystore/transports/grpc_asyncio.py +++ b/packages/google-cloud-memorystore/google/cloud/memorystore_v1/services/memorystore/transports/grpc_asyncio.py @@ -799,6 +799,76 @@ def backup_instance( ) return self._stubs["backup_instance"] + @property + def start_migration( + self, + ) -> Callable[ + [memorystore.StartMigrationRequest], Awaitable[operations_pb2.Operation] + ]: + r"""Return a callable for the start migration method over gRPC. + + Initiates the migration of a source instance to the + target Memorystore instance. + + After the successful completion of this operation, the + target instance will: + + 1. Set up replication with the source instance and + replicate any writes to the source instance. + 2. Only allow reads. + + Returns: + Callable[[~.StartMigrationRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "start_migration" not in self._stubs: + self._stubs["start_migration"] = self._logged_channel.unary_unary( + "/google.cloud.memorystore.v1.Memorystore/StartMigration", + request_serializer=memorystore.StartMigrationRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["start_migration"] + + @property + def finish_migration( + self, + ) -> Callable[ + [memorystore.FinishMigrationRequest], Awaitable[operations_pb2.Operation] + ]: + r"""Return a callable for the finish migration method over gRPC. + + Finalizes the migration process. + + After the successful completion of this operation, the + target instance will: + + 1. Stop replicating from the source instance. + 2. Allow both reads and writes. + + Returns: + Callable[[~.FinishMigrationRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "finish_migration" not in self._stubs: + self._stubs["finish_migration"] = self._logged_channel.unary_unary( + "/google.cloud.memorystore.v1.Memorystore/FinishMigration", + request_serializer=memorystore.FinishMigrationRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["finish_migration"] + def _prep_wrapped_messages(self, client_info): """Precompute the wrapped methods, overriding the base class method to use async wrappers.""" self._wrapped_methods = { @@ -904,6 +974,16 @@ def _prep_wrapped_messages(self, client_info): default_timeout=None, client_info=client_info, ), + self.start_migration: self._wrap_method( + self.start_migration, + default_timeout=None, + client_info=client_info, + ), + self.finish_migration: self._wrap_method( + self.finish_migration, + default_timeout=None, + client_info=client_info, + ), self.get_location: self._wrap_method( self.get_location, default_timeout=None, diff --git a/packages/google-cloud-memorystore/google/cloud/memorystore_v1/services/memorystore/transports/rest.py b/packages/google-cloud-memorystore/google/cloud/memorystore_v1/services/memorystore/transports/rest.py index 1ae3eaaa9717..92d8338de61d 100644 --- a/packages/google-cloud-memorystore/google/cloud/memorystore_v1/services/memorystore/transports/rest.py +++ b/packages/google-cloud-memorystore/google/cloud/memorystore_v1/services/memorystore/transports/rest.py @@ -114,6 +114,14 @@ def post_export_backup(self, response): logging.log(f"Received response: {response}") return response + def pre_finish_migration(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_finish_migration(self, response): + logging.log(f"Received response: {response}") + return response + def pre_get_backup(self, request, metadata): logging.log(f"Received request: {request}") return request, metadata @@ -186,6 +194,14 @@ def post_reschedule_maintenance(self, response): logging.log(f"Received response: {response}") return response + def pre_start_migration(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_start_migration(self, response): + logging.log(f"Received response: {response}") + return response + def pre_update_instance(self, request, metadata): logging.log(f"Received request: {request}") return request, metadata @@ -440,6 +456,54 @@ def post_export_backup_with_metadata( """ return response, metadata + def pre_finish_migration( + self, + request: memorystore.FinishMigrationRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + memorystore.FinishMigrationRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for finish_migration + + Override in a subclass to manipulate the request or metadata + before they are sent to the Memorystore server. + """ + return request, metadata + + def post_finish_migration( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for finish_migration + + DEPRECATED. Please use the `post_finish_migration_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the Memorystore server but before + it is returned to user code. This `post_finish_migration` interceptor runs + before the `post_finish_migration_with_metadata` interceptor. + """ + return response + + def post_finish_migration_with_metadata( + self, + response: operations_pb2.Operation, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for finish_migration + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the Memorystore server but before it is returned to user code. + + We recommend only using this `post_finish_migration_with_metadata` + interceptor in new development instead of the `post_finish_migration` interceptor. + When both interceptors are used, this `post_finish_migration_with_metadata` interceptor runs after the + `post_finish_migration` interceptor. The (possibly modified) response returned by + `post_finish_migration` will be passed to + `post_finish_migration_with_metadata`. + """ + return response, metadata + def pre_get_backup( self, request: memorystore.GetBackupRequest, @@ -878,6 +942,54 @@ def post_reschedule_maintenance_with_metadata( """ return response, metadata + def pre_start_migration( + self, + request: memorystore.StartMigrationRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + memorystore.StartMigrationRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for start_migration + + Override in a subclass to manipulate the request or metadata + before they are sent to the Memorystore server. + """ + return request, metadata + + def post_start_migration( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for start_migration + + DEPRECATED. Please use the `post_start_migration_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the Memorystore server but before + it is returned to user code. This `post_start_migration` interceptor runs + before the `post_start_migration_with_metadata` interceptor. + """ + return response + + def post_start_migration_with_metadata( + self, + response: operations_pb2.Operation, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for start_migration + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the Memorystore server but before it is returned to user code. + + We recommend only using this `post_start_migration_with_metadata` + interceptor in new development instead of the `post_start_migration` interceptor. + When both interceptors are used, this `post_start_migration_with_metadata` interceptor runs after the + `post_start_migration` interceptor. The (possibly modified) response returned by + `post_start_migration` will be passed to + `post_start_migration_with_metadata`. + """ + return response, metadata + def pre_update_instance( self, request: memorystore.UpdateInstanceRequest, @@ -1260,7 +1372,7 @@ def __call__( Args: request (~.memorystore.BackupInstanceRequest): - The request object. Request for [BackupInstance]. + The request object. Request for ``BackupInstance``. retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -1561,7 +1673,7 @@ def __call__( Args: request (~.memorystore.DeleteBackupRequest): - The request object. Request for [DeleteBackup]. + The request object. Request for ``DeleteBackup``. retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -1856,7 +1968,7 @@ def __call__( Args: request (~.memorystore.ExportBackupRequest): - The request object. Request for [ExportBackup]. + The request object. Request for ``ExportBackup``. retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -1972,6 +2084,159 @@ def __call__( ) return resp + class _FinishMigration( + _BaseMemorystoreRestTransport._BaseFinishMigration, MemorystoreRestStub + ): + def __hash__(self): + return hash("MemorystoreRestTransport.FinishMigration") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: memorystore.FinishMigrationRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + r"""Call the finish migration method over HTTP. + + Args: + request (~.memorystore.FinishMigrationRequest): + The request object. Request for ``FinishMigration``. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options = ( + _BaseMemorystoreRestTransport._BaseFinishMigration._get_http_options() + ) + + request, metadata = self._interceptor.pre_finish_migration( + request, metadata + ) + transcoded_request = _BaseMemorystoreRestTransport._BaseFinishMigration._get_transcoded_request( + http_options, request + ) + + body = _BaseMemorystoreRestTransport._BaseFinishMigration._get_request_body_json( + transcoded_request + ) + + # Jsonify the query params + query_params = _BaseMemorystoreRestTransport._BaseFinishMigration._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.memorystore_v1.MemorystoreClient.FinishMigration", + extra={ + "serviceName": "google.cloud.memorystore.v1.Memorystore", + "rpcName": "FinishMigration", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = MemorystoreRestTransport._FinishMigration._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_finish_migration(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_finish_migration_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.memorystore_v1.MemorystoreClient.finish_migration", + extra={ + "serviceName": "google.cloud.memorystore.v1.Memorystore", + "rpcName": "FinishMigration", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + class _GetBackup(_BaseMemorystoreRestTransport._BaseGetBackup, MemorystoreRestStub): def __hash__(self): return hash("MemorystoreRestTransport.GetBackup") @@ -2010,7 +2275,7 @@ def __call__( Args: request (~.memorystore.GetBackupRequest): - The request object. Request for [GetBackup]. + The request object. Request for ``GetBackup``. retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -2158,7 +2423,7 @@ def __call__( Args: request (~.memorystore.GetBackupCollectionRequest): - The request object. Request for [GetBackupCollection]. + The request object. Request for ``GetBackupCollection``. retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -2302,7 +2567,7 @@ def __call__( Args: request (~.memorystore.GetCertificateAuthorityRequest): - The request object. Request message for [GetCertificateAuthority][]. + The request object. Request message for ``GetCertificateAuthority``. retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -2602,8 +2867,7 @@ def __call__( Args: request (~.memorystore.GetSharedRegionalCertificateAuthorityRequest): - The request object. Request for - [GetSharedRegionalCertificateAuthority][google.cloud.memorystore.v1.Memorystore.GetSharedRegionalCertificateAuthority]. + The request object. Request for ``GetSharedRegionalCertificateAuthority``. retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -2757,7 +3021,7 @@ def __call__( Args: request (~.memorystore.ListBackupCollectionsRequest): - The request object. Request for [ListBackupCollections] + The request object. Request for ``ListBackupCollections``. retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -2768,7 +3032,7 @@ def __call__( Returns: ~.memorystore.ListBackupCollectionsResponse: - Response for [ListBackupCollections]. + Response for ``ListBackupCollections``. """ http_options = _BaseMemorystoreRestTransport._BaseListBackupCollections._get_http_options() @@ -2903,7 +3167,7 @@ def __call__( Args: request (~.memorystore.ListBackupsRequest): - The request object. Request for [ListBackups]. + The request object. Request for ``ListBackups``. retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -2914,7 +3178,7 @@ def __call__( Returns: ~.memorystore.ListBackupsResponse: - Response for [ListBackups]. + Response for ``ListBackups``. """ http_options = ( @@ -3062,7 +3326,7 @@ def __call__( Returns: ~.memorystore.ListInstancesResponse: - Response message for [ListInstances][]. + Response message for ``ListInstances``. """ http_options = ( @@ -3311,6 +3575,157 @@ def __call__( ) return resp + class _StartMigration( + _BaseMemorystoreRestTransport._BaseStartMigration, MemorystoreRestStub + ): + def __hash__(self): + return hash("MemorystoreRestTransport.StartMigration") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: memorystore.StartMigrationRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + r"""Call the start migration method over HTTP. + + Args: + request (~.memorystore.StartMigrationRequest): + The request object. Request for ``StartMigration``. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options = ( + _BaseMemorystoreRestTransport._BaseStartMigration._get_http_options() + ) + + request, metadata = self._interceptor.pre_start_migration(request, metadata) + transcoded_request = _BaseMemorystoreRestTransport._BaseStartMigration._get_transcoded_request( + http_options, request + ) + + body = _BaseMemorystoreRestTransport._BaseStartMigration._get_request_body_json( + transcoded_request + ) + + # Jsonify the query params + query_params = _BaseMemorystoreRestTransport._BaseStartMigration._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_v1.MemorystoreClient.StartMigration", + extra={ + "serviceName": "google.cloud.memorystore.v1.Memorystore", + "rpcName": "StartMigration", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = MemorystoreRestTransport._StartMigration._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_start_migration(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_start_migration_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.memorystore_v1.MemorystoreClient.start_migration", + extra={ + "serviceName": "google.cloud.memorystore.v1.Memorystore", + "rpcName": "StartMigration", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + class _UpdateInstance( _BaseMemorystoreRestTransport._BaseUpdateInstance, MemorystoreRestStub ): @@ -3502,6 +3917,14 @@ def export_backup( # In C++ this would require a dynamic_cast return self._ExportBackup(self._session, self._host, self._interceptor) # type: ignore + @property + def finish_migration( + self, + ) -> Callable[[memorystore.FinishMigrationRequest], operations_pb2.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._FinishMigration(self._session, self._host, self._interceptor) # type: ignore + @property def get_backup( self, @@ -3590,6 +4013,14 @@ def reschedule_maintenance( # In C++ this would require a dynamic_cast return self._RescheduleMaintenance(self._session, self._host, self._interceptor) # type: ignore + @property + def start_migration( + self, + ) -> Callable[[memorystore.StartMigrationRequest], operations_pb2.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._StartMigration(self._session, self._host, self._interceptor) # type: ignore + @property def update_instance( self, diff --git a/packages/google-cloud-memorystore/google/cloud/memorystore_v1/services/memorystore/transports/rest_base.py b/packages/google-cloud-memorystore/google/cloud/memorystore_v1/services/memorystore/transports/rest_base.py index 052a03272603..7b0c2c0c8f52 100644 --- a/packages/google-cloud-memorystore/google/cloud/memorystore_v1/services/memorystore/transports/rest_base.py +++ b/packages/google-cloud-memorystore/google/cloud/memorystore_v1/services/memorystore/transports/rest_base.py @@ -356,6 +356,63 @@ def _get_query_params_json(transcoded_request): query_params["$alt"] = "json;enum-encoding=int" return query_params + class _BaseFinishMigration: + 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=projects/*/locations/*/instances/*}:finishMigration", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = memorystore.FinishMigrationRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseMemorystoreRestTransport._BaseFinishMigration._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + class _BaseGetBackup: def __hash__(self): # pragma: NO COVER return NotImplementedError("__hash__ must be implemented.") @@ -791,6 +848,63 @@ def _get_query_params_json(transcoded_request): query_params["$alt"] = "json;enum-encoding=int" return query_params + class _BaseStartMigration: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1/{name=projects/*/locations/*/instances/*}:startMigration", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = memorystore.StartMigrationRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseMemorystoreRestTransport._BaseStartMigration._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + class _BaseUpdateInstance: def __hash__(self): # pragma: NO COVER return NotImplementedError("__hash__ must be implemented.") diff --git a/packages/google-cloud-memorystore/google/cloud/memorystore_v1/types/__init__.py b/packages/google-cloud-memorystore/google/cloud/memorystore_v1/types/__init__.py index a4279d8c85e9..f27dae9cf6ce 100644 --- a/packages/google-cloud-memorystore/google/cloud/memorystore_v1/types/__init__.py +++ b/packages/google-cloud-memorystore/google/cloud/memorystore_v1/types/__init__.py @@ -28,6 +28,7 @@ DiscoveryEndpoint, EncryptionInfo, ExportBackupRequest, + FinishMigrationRequest, GetBackupCollectionRequest, GetBackupRequest, GetCertificateAuthorityRequest, @@ -42,6 +43,7 @@ ListInstancesResponse, MaintenancePolicy, MaintenanceSchedule, + MigrationConfig, NodeConfig, OperationMetadata, PersistenceConfig, @@ -50,7 +52,9 @@ PscConnection, PscConnectionStatus, RescheduleMaintenanceRequest, + SelfManagedSource, SharedRegionalCertificateAuthority, + StartMigrationRequest, UpdateInstanceRequest, WeeklyMaintenanceWindow, ZoneDistributionConfig, @@ -70,6 +74,7 @@ "DiscoveryEndpoint", "EncryptionInfo", "ExportBackupRequest", + "FinishMigrationRequest", "GetBackupCollectionRequest", "GetBackupRequest", "GetCertificateAuthorityRequest", @@ -84,6 +89,7 @@ "ListInstancesResponse", "MaintenancePolicy", "MaintenanceSchedule", + "MigrationConfig", "NodeConfig", "OperationMetadata", "PersistenceConfig", @@ -91,7 +97,9 @@ "PscAutoConnection", "PscConnection", "RescheduleMaintenanceRequest", + "SelfManagedSource", "SharedRegionalCertificateAuthority", + "StartMigrationRequest", "UpdateInstanceRequest", "WeeklyMaintenanceWindow", "ZoneDistributionConfig", diff --git a/packages/google-cloud-memorystore/google/cloud/memorystore_v1/types/memorystore.py b/packages/google-cloud-memorystore/google/cloud/memorystore_v1/types/memorystore.py index f17458a7cdc7..383da335b787 100644 --- a/packages/google-cloud-memorystore/google/cloud/memorystore_v1/types/memorystore.py +++ b/packages/google-cloud-memorystore/google/cloud/memorystore_v1/types/memorystore.py @@ -30,6 +30,10 @@ "PscConnectionStatus", "ConnectionType", "Instance", + "StartMigrationRequest", + "FinishMigrationRequest", + "SelfManagedSource", + "MigrationConfig", "AutomatedBackupConfig", "BackupCollection", "Backup", @@ -209,7 +213,8 @@ class Instance(proto.Message): endpoints (MutableSequence[google.cloud.memorystore_v1.types.Instance.InstanceEndpoint]): Optional. Endpoints for the instance. mode (google.cloud.memorystore_v1.types.Instance.Mode): - Optional. The mode config for the instance. + Optional. Immutable. The mode config for the + instance. simulate_maintenance_event (bool): Optional. Input only. Simulate a maintenance event. @@ -301,6 +306,9 @@ class Instance(proto.Message): certificates. This field is a member of `oneof`_ ``_rotate_server_certificate``. + migration_config (google.cloud.memorystore_v1.types.MigrationConfig): + Output only. Migration config for the + instance. """ class State(proto.Enum): @@ -317,6 +325,8 @@ class State(proto.Enum): Instance is being updated. DELETING (4): Instance is being deleted. + MIGRATING (6): + Instance is being migrated. """ STATE_UNSPECIFIED = 0 @@ -324,6 +334,7 @@ class State(proto.Enum): ACTIVE = 2 UPDATING = 3 DELETING = 4 + MIGRATING = 6 class AuthorizationMode(proto.Enum): r"""Possible authorization modes of the instance. @@ -383,7 +394,7 @@ class NodeType(proto.Enum): STANDARD_LARGE (8): Standard large. HIGHMEM_2XLARGE (9): - High memory 2x large. + High memory 2xlarge. CUSTOM_PICO (10): Custom pico. """ @@ -831,6 +842,182 @@ class ConnectionDetail(proto.Message): number=58, optional=True, ) + migration_config: "MigrationConfig" = proto.Field( + proto.MESSAGE, + number=59, + message="MigrationConfig", + ) + + +class StartMigrationRequest(proto.Message): + r"""Request for ``StartMigration``. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + self_managed_source (google.cloud.memorystore_v1.types.SelfManagedSource): + Required. Configuration for migrating from a + self-managed Valkey/Redis instance + + This field is a member of `oneof`_ ``source``. + name (str): + Required. The resource name of the instance + to start migration on. Format: + projects/{project}/locations/{location}/instances/{instance} + """ + + self_managed_source: "SelfManagedSource" = proto.Field( + proto.MESSAGE, + number=2, + oneof="source", + message="SelfManagedSource", + ) + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class FinishMigrationRequest(proto.Message): + r"""Request for ``FinishMigration``. + + Attributes: + name (str): + Required. The resource name of the instance + to finalize migration on. Format: + projects/{project}/locations/{location}/instances/{instance} + force (bool): + Optional. By default, the ``FinishMigration`` operation + ensures the target replication offset to catch up to the + source offset as of the time of the call. Set this field to + ``true`` to bypass this offset verification check. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + force: bool = proto.Field( + proto.BOOL, + number=2, + ) + + +class SelfManagedSource(proto.Message): + r"""Details of the self-managed source instance. + + Attributes: + ip_address (str): + Required. The IP address of the source + instance. This IP address should be a stable IP + address that can be accessed by the Memorystore + instance throughout the migration process. + port (int): + Required. The port of the source instance. + This port should be a stable port that can be + accessed by the Memorystore instance throughout + the migration process. + network_attachment (str): + Required. The resource name of the Private Service Connect + Network Attachment used to establish connectivity to the + source instance. This network attachment has the following + requirements: + + 1. It must be in the same project as the Memorystore + instance. + 2. It must be in the same region as the Memorystore + instance. + 3. The subnet attached to the network attachment must be in + the same VPC network as the source instance nodes. + + Format: + projects/{project}/regions/{region}/networkAttachments/{network_attachment} + """ + + ip_address: str = proto.Field( + proto.STRING, + number=1, + ) + port: int = proto.Field( + proto.INT32, + number=2, + ) + network_attachment: str = proto.Field( + proto.STRING, + number=3, + ) + + +class MigrationConfig(proto.Message): + r"""Configuration for the migration of an instance. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + self_managed_source (google.cloud.memorystore_v1.types.SelfManagedSource): + Output only. Configuration for migrating from + a self-managed Valkey/Redis instance + + This field is a member of `oneof`_ ``source``. + state (google.cloud.memorystore_v1.types.MigrationConfig.State): + Output only. Migration state of the instance. + force_finish_migration (bool): + Output only. Represents a boolean flag to + force migration finalization without offset + catch up validation between source and target + before stopping replication. + """ + + class State(proto.Enum): + r"""Migration state of the instance. + New values may be added in the future. + + Values: + STATE_UNSPECIFIED (0): + Instance has no migration related activity. + This is the initial state. + ROLLED_BACK (1): + Instance is not currently migrating. The + instance underwent a migration attempt that + failed, and the subsequent rollback was + successful. The instance is now ready for a new + migration attempt if desired. + ROLLING_BACK (5): + Indicates a previous migration attempt failed. The + high-level instance state will be ``MIGRATING``. The + instance is not ready for a new migration attempt. Rollback + is in progress to restore the instance to its original + state. The instance will remain in this state until rollback + is successful. + REPLICATION_ESTABLISHED (6): + Instance is in the process of migration. + Instance has established successful replication + and is ready for cutover. + MIGRATED (4): + Instance is successfully migrated. + """ + + STATE_UNSPECIFIED = 0 + ROLLED_BACK = 1 + ROLLING_BACK = 5 + REPLICATION_ESTABLISHED = 6 + MIGRATED = 4 + + self_managed_source: "SelfManagedSource" = proto.Field( + proto.MESSAGE, + number=2, + oneof="source", + message="SelfManagedSource", + ) + state: State = proto.Field( + proto.ENUM, + number=1, + enum=State, + ) + force_finish_migration: bool = proto.Field( + proto.BOOL, + number=4, + ) class AutomatedBackupConfig(proto.Message): @@ -1448,7 +1635,7 @@ class PscAutoConnection(proto.Message): network (str): Required. The network where the PSC endpoints are created, in the form of - projects/{project_id}/global/networks/{network_id}. + projects/{project_id}/global/networks/{network_name}. service_attachment (str): Output only. The service attachment which is the target of the PSC connection, in the form of @@ -1533,7 +1720,7 @@ class PscConnection(proto.Message): network (str): Required. The consumer network where the IP address resides, in the form of - projects/{project_id}/global/networks/{network_id}. + projects/{project_id}/global/networks/{network_name}. service_attachment (str): Required. The service attachment which is the target of the PSC connection, in the form of @@ -1604,7 +1791,7 @@ class DiscoveryEndpoint(proto.Message): network (str): Output only. The network where the IP address of the discovery endpoint will be reserved, in the form of - projects/{network_project}/global/networks/{network_id}. + projects/{network_project}/global/networks/{network_name}. """ address: str = proto.Field( @@ -1908,7 +2095,7 @@ class ListInstancesRequest(proto.Message): class ListInstancesResponse(proto.Message): - r"""Response message for [ListInstances][]. + r"""Response message for ``ListInstances``. Attributes: instances (MutableSequence[google.cloud.memorystore_v1.types.Instance]): @@ -2110,7 +2297,7 @@ class DeleteInstanceRequest(proto.Message): class ListBackupCollectionsRequest(proto.Message): - r"""Request for [ListBackupCollections] + r"""Request for ``ListBackupCollections``. Attributes: parent (str): @@ -2124,12 +2311,11 @@ class ListBackupCollectionsRequest(proto.Message): If not specified, a default value of 1000 will be used by the service. Regardless of the page_size value, the response may include a partial list and a caller should only rely on - response's - [``next_page_token``][google.cloud.memorystore.v1.ListBackupCollectionsResponse.next_page_token] - to determine if there are more clusters left to be queried. + response's ``next_page_token`` to determine if there are + more clusters left to be queried. page_token (str): Optional. The ``next_page_token`` value returned from a - previous [ListBackupCollections] request, if any. + previous ``ListBackupCollections`` request, if any. """ parent: str = proto.Field( @@ -2147,7 +2333,7 @@ class ListBackupCollectionsRequest(proto.Message): class ListBackupCollectionsResponse(proto.Message): - r"""Response for [ListBackupCollections]. + r"""Response for ``ListBackupCollections``. Attributes: backup_collections (MutableSequence[google.cloud.memorystore_v1.types.BackupCollection]): @@ -2191,7 +2377,7 @@ def raw_page(self): class GetBackupCollectionRequest(proto.Message): - r"""Request for [GetBackupCollection]. + r"""Request for ``GetBackupCollection``. Attributes: name (str): @@ -2208,7 +2394,7 @@ class GetBackupCollectionRequest(proto.Message): class ListBackupsRequest(proto.Message): - r"""Request for [ListBackups]. + r"""Request for ``ListBackups``. Attributes: parent (str): @@ -2221,12 +2407,11 @@ class ListBackupsRequest(proto.Message): If not specified, a default value of 1000 will be used by the service. Regardless of the page_size value, the response may include a partial list and a caller should only rely on - response's - [``next_page_token``][google.cloud.memorystore.v1.ListBackupsResponse.next_page_token] - to determine if there are more clusters left to be queried. + response's ``next_page_token`` to determine if there are + more clusters left to be queried. page_token (str): Optional. The ``next_page_token`` value returned from a - previous [ListBackupCollections] request, if any. + previous ``ListBackupCollections`` request, if any. """ parent: str = proto.Field( @@ -2244,7 +2429,7 @@ class ListBackupsRequest(proto.Message): class ListBackupsResponse(proto.Message): - r"""Response for [ListBackups]. + r"""Response for ``ListBackups``. Attributes: backups (MutableSequence[google.cloud.memorystore_v1.types.Backup]): @@ -2277,7 +2462,7 @@ def raw_page(self): class GetBackupRequest(proto.Message): - r"""Request for [GetBackup]. + r"""Request for ``GetBackup``. Attributes: name (str): @@ -2292,7 +2477,7 @@ class GetBackupRequest(proto.Message): class DeleteBackupRequest(proto.Message): - r"""Request for [DeleteBackup]. + r"""Request for ``DeleteBackup``. Attributes: name (str): @@ -2313,7 +2498,7 @@ class DeleteBackupRequest(proto.Message): class ExportBackupRequest(proto.Message): - r"""Request for [ExportBackup]. + r"""Request for ``ExportBackup``. .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields @@ -2340,7 +2525,7 @@ class ExportBackupRequest(proto.Message): class BackupInstanceRequest(proto.Message): - r"""Request for [BackupInstance]. + r"""Request for ``BackupInstance``. .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields @@ -2378,7 +2563,7 @@ class BackupInstanceRequest(proto.Message): class GetCertificateAuthorityRequest(proto.Message): - r"""Request message for [GetCertificateAuthority][]. + r"""Request message for ``GetCertificateAuthority``. Attributes: name (str): @@ -2517,8 +2702,7 @@ class RegionalCertChain(proto.Message): class GetSharedRegionalCertificateAuthorityRequest(proto.Message): - r"""Request for - [GetSharedRegionalCertificateAuthority][google.cloud.memorystore.v1.Memorystore.GetSharedRegionalCertificateAuthority]. + r"""Request for ``GetSharedRegionalCertificateAuthority``. Attributes: name (str): diff --git a/packages/google-cloud-memorystore/samples/generated_samples/memorystore_v1_generated_memorystore_finish_migration_async.py b/packages/google-cloud-memorystore/samples/generated_samples/memorystore_v1_generated_memorystore_finish_migration_async.py new file mode 100644 index 000000000000..0fc6383e6345 --- /dev/null +++ b/packages/google-cloud-memorystore/samples/generated_samples/memorystore_v1_generated_memorystore_finish_migration_async.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for FinishMigration +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-memorystore + + +# [START memorystore_v1_generated_Memorystore_FinishMigration_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import memorystore_v1 + + +async def sample_finish_migration(): + # Create a client + client = memorystore_v1.MemorystoreAsyncClient() + + # Initialize request argument(s) + request = memorystore_v1.FinishMigrationRequest( + name="name_value", + ) + + # Make the request + operation = await client.finish_migration(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + + +# [END memorystore_v1_generated_Memorystore_FinishMigration_async] diff --git a/packages/google-cloud-memorystore/samples/generated_samples/memorystore_v1_generated_memorystore_finish_migration_sync.py b/packages/google-cloud-memorystore/samples/generated_samples/memorystore_v1_generated_memorystore_finish_migration_sync.py new file mode 100644 index 000000000000..5ed2b5aeda25 --- /dev/null +++ b/packages/google-cloud-memorystore/samples/generated_samples/memorystore_v1_generated_memorystore_finish_migration_sync.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for FinishMigration +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-memorystore + + +# [START memorystore_v1_generated_Memorystore_FinishMigration_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import memorystore_v1 + + +def sample_finish_migration(): + # Create a client + client = memorystore_v1.MemorystoreClient() + + # Initialize request argument(s) + request = memorystore_v1.FinishMigrationRequest( + name="name_value", + ) + + # Make the request + operation = client.finish_migration(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + +# [END memorystore_v1_generated_Memorystore_FinishMigration_sync] diff --git a/packages/google-cloud-memorystore/samples/generated_samples/memorystore_v1_generated_memorystore_start_migration_async.py b/packages/google-cloud-memorystore/samples/generated_samples/memorystore_v1_generated_memorystore_start_migration_async.py new file mode 100644 index 000000000000..716cbb507bf8 --- /dev/null +++ b/packages/google-cloud-memorystore/samples/generated_samples/memorystore_v1_generated_memorystore_start_migration_async.py @@ -0,0 +1,63 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for StartMigration +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-memorystore + + +# [START memorystore_v1_generated_Memorystore_StartMigration_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import memorystore_v1 + + +async def sample_start_migration(): + # Create a client + client = memorystore_v1.MemorystoreAsyncClient() + + # Initialize request argument(s) + self_managed_source = memorystore_v1.SelfManagedSource() + self_managed_source.ip_address = "ip_address_value" + self_managed_source.port = 453 + self_managed_source.network_attachment = "network_attachment_value" + + request = memorystore_v1.StartMigrationRequest( + self_managed_source=self_managed_source, + name="name_value", + ) + + # Make the request + operation = await client.start_migration(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + + +# [END memorystore_v1_generated_Memorystore_StartMigration_async] diff --git a/packages/google-cloud-memorystore/samples/generated_samples/memorystore_v1_generated_memorystore_start_migration_sync.py b/packages/google-cloud-memorystore/samples/generated_samples/memorystore_v1_generated_memorystore_start_migration_sync.py new file mode 100644 index 000000000000..f5477b44f459 --- /dev/null +++ b/packages/google-cloud-memorystore/samples/generated_samples/memorystore_v1_generated_memorystore_start_migration_sync.py @@ -0,0 +1,63 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for StartMigration +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-memorystore + + +# [START memorystore_v1_generated_Memorystore_StartMigration_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import memorystore_v1 + + +def sample_start_migration(): + # Create a client + client = memorystore_v1.MemorystoreClient() + + # Initialize request argument(s) + self_managed_source = memorystore_v1.SelfManagedSource() + self_managed_source.ip_address = "ip_address_value" + self_managed_source.port = 453 + self_managed_source.network_attachment = "network_attachment_value" + + request = memorystore_v1.StartMigrationRequest( + self_managed_source=self_managed_source, + name="name_value", + ) + + # Make the request + operation = client.start_migration(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + +# [END memorystore_v1_generated_Memorystore_StartMigration_sync] diff --git a/packages/google-cloud-memorystore/samples/generated_samples/snippet_metadata_google.cloud.memorystore.v1.json b/packages/google-cloud-memorystore/samples/generated_samples/snippet_metadata_google.cloud.memorystore.v1.json index f8fa12a1ea5b..bf07510ce1b0 100644 --- a/packages/google-cloud-memorystore/samples/generated_samples/snippet_metadata_google.cloud.memorystore.v1.json +++ b/packages/google-cloud-memorystore/samples/generated_samples/snippet_metadata_google.cloud.memorystore.v1.json @@ -824,6 +824,175 @@ ], "title": "memorystore_v1_generated_memorystore_export_backup_sync.py" }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.memorystore_v1.MemorystoreAsyncClient", + "shortName": "MemorystoreAsyncClient" + }, + "fullName": "google.cloud.memorystore_v1.MemorystoreAsyncClient.finish_migration", + "method": { + "fullName": "google.cloud.memorystore.v1.Memorystore.FinishMigration", + "service": { + "fullName": "google.cloud.memorystore.v1.Memorystore", + "shortName": "Memorystore" + }, + "shortName": "FinishMigration" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.memorystore_v1.types.FinishMigrationRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "force", + "type": "bool" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "finish_migration" + }, + "description": "Sample for FinishMigration", + "file": "memorystore_v1_generated_memorystore_finish_migration_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "memorystore_v1_generated_Memorystore_FinishMigration_async", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "memorystore_v1_generated_memorystore_finish_migration_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.memorystore_v1.MemorystoreClient", + "shortName": "MemorystoreClient" + }, + "fullName": "google.cloud.memorystore_v1.MemorystoreClient.finish_migration", + "method": { + "fullName": "google.cloud.memorystore.v1.Memorystore.FinishMigration", + "service": { + "fullName": "google.cloud.memorystore.v1.Memorystore", + "shortName": "Memorystore" + }, + "shortName": "FinishMigration" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.memorystore_v1.types.FinishMigrationRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "force", + "type": "bool" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "finish_migration" + }, + "description": "Sample for FinishMigration", + "file": "memorystore_v1_generated_memorystore_finish_migration_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "memorystore_v1_generated_Memorystore_FinishMigration_sync", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "memorystore_v1_generated_memorystore_finish_migration_sync.py" + }, { "canonical": true, "clientMethod": { @@ -2289,6 +2458,159 @@ ], "title": "memorystore_v1_generated_memorystore_reschedule_maintenance_sync.py" }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.memorystore_v1.MemorystoreAsyncClient", + "shortName": "MemorystoreAsyncClient" + }, + "fullName": "google.cloud.memorystore_v1.MemorystoreAsyncClient.start_migration", + "method": { + "fullName": "google.cloud.memorystore.v1.Memorystore.StartMigration", + "service": { + "fullName": "google.cloud.memorystore.v1.Memorystore", + "shortName": "Memorystore" + }, + "shortName": "StartMigration" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.memorystore_v1.types.StartMigrationRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "start_migration" + }, + "description": "Sample for StartMigration", + "file": "memorystore_v1_generated_memorystore_start_migration_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "memorystore_v1_generated_Memorystore_StartMigration_async", + "segments": [ + { + "end": 61, + "start": 27, + "type": "FULL" + }, + { + "end": 61, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 51, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 58, + "start": 52, + "type": "REQUEST_EXECUTION" + }, + { + "end": 62, + "start": 59, + "type": "RESPONSE_HANDLING" + } + ], + "title": "memorystore_v1_generated_memorystore_start_migration_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.memorystore_v1.MemorystoreClient", + "shortName": "MemorystoreClient" + }, + "fullName": "google.cloud.memorystore_v1.MemorystoreClient.start_migration", + "method": { + "fullName": "google.cloud.memorystore.v1.Memorystore.StartMigration", + "service": { + "fullName": "google.cloud.memorystore.v1.Memorystore", + "shortName": "Memorystore" + }, + "shortName": "StartMigration" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.memorystore_v1.types.StartMigrationRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "start_migration" + }, + "description": "Sample for StartMigration", + "file": "memorystore_v1_generated_memorystore_start_migration_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "memorystore_v1_generated_Memorystore_StartMigration_sync", + "segments": [ + { + "end": 61, + "start": 27, + "type": "FULL" + }, + { + "end": 61, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 51, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 58, + "start": 52, + "type": "REQUEST_EXECUTION" + }, + { + "end": 62, + "start": 59, + "type": "RESPONSE_HANDLING" + } + ], + "title": "memorystore_v1_generated_memorystore_start_migration_sync.py" + }, { "canonical": true, "clientMethod": { diff --git a/packages/google-cloud-memorystore/tests/unit/gapic/memorystore_v1/test_memorystore.py b/packages/google-cloud-memorystore/tests/unit/gapic/memorystore_v1/test_memorystore.py index dbd31326d61e..fc539401ffb3 100644 --- a/packages/google-cloud-memorystore/tests/unit/gapic/memorystore_v1/test_memorystore.py +++ b/packages/google-cloud-memorystore/tests/unit/gapic/memorystore_v1/test_memorystore.py @@ -1286,7 +1286,11 @@ def test_memorystore_client_create_channel_credentials_file( credentials=file_creds, credentials_file=None, quota_project_id=None, - default_scopes=("https://www.googleapis.com/auth/cloud-platform",), + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/memorystore.read-only", + "https://www.googleapis.com/auth/memorystore.read-write", + ), scopes=None, default_host="memorystore.googleapis.com", ssl_credentials=None, @@ -7066,13 +7070,75 @@ async def test_backup_instance_flattened_error_async(): ) -def test_list_instances_rest_use_cached_wrapped_rpc(): +@pytest.mark.parametrize( + "request_type", + [ + memorystore.StartMigrationRequest(), + {}, + ], +) +def test_start_migration(request_type, transport: str = "grpc"): + client = MemorystoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.start_migration), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/spam") + response = client.start_migration(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = memorystore.StartMigrationRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_start_migration_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = MemorystoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = memorystore.StartMigrationRequest( + name="name_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.start_migration), "__call__") as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.start_migration(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = memorystore.StartMigrationRequest( + name="name_value", + ) + assert args[0] == request_msg + + +def test_start_migration_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: client = MemorystoreClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport="grpc", ) # Should wrap all calls on client creation @@ -7080,141 +7146,1116 @@ def test_list_instances_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.list_instances in client._transport._wrapped_methods + assert client._transport.start_migration in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.Mock() mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.list_instances] = mock_rpc - + client._transport._wrapped_methods[client._transport.start_migration] = mock_rpc request = {} - client.list_instances(request) + client.start_migration(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.list_instances(request) + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.start_migration(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_list_instances_rest_required_fields( - request_type=memorystore.ListInstancesRequest, +@pytest.mark.asyncio +async def test_start_migration_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", ): - transport_class = transports.MemorystoreRestTransport + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = MemorystoreAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) - request_init = {} - request_init["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.start_migration + in client._client._transport._wrapped_methods + ) - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).list_instances._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.start_migration + ] = mock_rpc - # verify required fields with default values are now present + request = {} + await client.start_migration(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_instances._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set( - ( - "filter", - "order_by", - "page_size", - "page_token", - ) + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.start_migration(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "request_type", + [ + memorystore.StartMigrationRequest(), + {}, + ], +) +async def test_start_migration_async(request_type, transport: str = "grpc_asyncio"): + client = MemorystoreAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, ) - 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.start_migration), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + response = await client.start_migration(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = memorystore.StartMigrationRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + +def test_start_migration_field_headers(): client = MemorystoreClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = memorystore.ListInstancesResponse() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, "request") as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, "transcode") as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - "uri": "v1/sample_method", - "method": "get", - "query_params": pb_request, - } - transcode.return_value = transcode_result - response_value = Response() - response_value.status_code = 200 + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = memorystore.StartMigrationRequest() - # Convert return value to protobuf type - return_value = memorystore.ListInstancesResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) + request.name = "name_value" - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.start_migration), "__call__") as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.start_migration(request) - response = client.list_instances(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request - expected_params = [("$alt", "json;enum-encoding=int")] - actual_params = req.call_args.kwargs["params"] - assert sorted(expected_params) == sorted(actual_params) + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] -def test_list_instances_rest_unset_required_fields(): - transport = transports.MemorystoreRestTransport( - credentials=ga_credentials.AnonymousCredentials +@pytest.mark.asyncio +async def test_start_migration_field_headers_async(): + client = MemorystoreAsyncClient( + credentials=async_anonymous_credentials(), ) - unset_fields = transport.list_instances._get_unset_required_fields({}) - assert set(unset_fields) == ( - set( - ( - "filter", - "orderBy", - "pageSize", - "pageToken", - ) + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = memorystore.StartMigrationRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.start_migration), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/op") ) - & set(("parent",)) - ) + await client.start_migration(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request -def test_list_instances_rest_flattened(): + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] + + +@pytest.mark.parametrize( + "request_type", + [ + memorystore.FinishMigrationRequest(), + {}, + ], +) +def test_finish_migration(request_type, transport: str = "grpc"): client = MemorystoreClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport=transport, ) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), "request") as req: + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.finish_migration), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/spam") + response = client.finish_migration(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = memorystore.FinishMigrationRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_finish_migration_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = MemorystoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = memorystore.FinishMigrationRequest( + name="name_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.finish_migration), "__call__") as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.finish_migration(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = memorystore.FinishMigrationRequest( + name="name_value", + ) + assert args[0] == request_msg + + +def test_finish_migration_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = MemorystoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.finish_migration in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.finish_migration] = ( + mock_rpc + ) + request = {} + client.finish_migration(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.finish_migration(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_finish_migration_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = MemorystoreAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.finish_migration + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.finish_migration + ] = mock_rpc + + request = {} + await client.finish_migration(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.finish_migration(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "request_type", + [ + memorystore.FinishMigrationRequest(), + {}, + ], +) +async def test_finish_migration_async(request_type, transport: str = "grpc_asyncio"): + client = MemorystoreAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.finish_migration), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + response = await client.finish_migration(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = memorystore.FinishMigrationRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_finish_migration_field_headers(): + client = MemorystoreClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = memorystore.FinishMigrationRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.finish_migration), "__call__") as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.finish_migration(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_finish_migration_field_headers_async(): + client = MemorystoreAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = memorystore.FinishMigrationRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.finish_migration), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/op") + ) + await client.finish_migration(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] + + +def test_finish_migration_flattened(): + client = MemorystoreClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.finish_migration), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/op") + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.finish_migration( + name="name_value", + force=True, + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + arg = args[0].force + mock_val = True + assert arg == mock_val + + +def test_finish_migration_flattened_error(): + client = MemorystoreClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.finish_migration( + memorystore.FinishMigrationRequest(), + name="name_value", + force=True, + ) + + +@pytest.mark.asyncio +async def test_finish_migration_flattened_async(): + client = MemorystoreAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.finish_migration), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/op") + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.finish_migration( + name="name_value", + force=True, + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + arg = args[0].force + mock_val = True + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_finish_migration_flattened_error_async(): + client = MemorystoreAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.finish_migration( + memorystore.FinishMigrationRequest(), + name="name_value", + force=True, + ) + + +def test_list_instances_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = MemorystoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_instances in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.list_instances] = mock_rpc + + request = {} + client.list_instances(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_instances(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_list_instances_rest_required_fields( + request_type=memorystore.ListInstancesRequest, +): + transport_class = transports.MemorystoreRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).list_instances._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = "parent_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).list_instances._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "filter", + "order_by", + "page_size", + "page_token", + ) + ) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + + client = MemorystoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = memorystore.ListInstancesResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "get", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = memorystore.ListInstancesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.list_instances(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_list_instances_rest_unset_required_fields(): + transport = transports.MemorystoreRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.list_instances._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "filter", + "orderBy", + "pageSize", + "pageToken", + ) + ) + & set(("parent",)) + ) + + +def test_list_instances_rest_flattened(): + client = MemorystoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = memorystore.ListInstancesResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {"parent": "projects/sample1/locations/sample2"} + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = memorystore.ListInstancesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.list_instances(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1/{parent=projects/*/locations/*}/instances" % client.transport._host, + args[1], + ) + + +def test_list_instances_rest_flattened_error(transport: str = "rest"): + client = MemorystoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_instances( + memorystore.ListInstancesRequest(), + parent="parent_value", + ) + + +def test_list_instances_rest_pager(transport: str = "rest"): + client = MemorystoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # TODO(kbandes): remove this mock unless there's a good reason for it. + # with mock.patch.object(path_template, 'transcode') as transcode: + # Set the response as a series of pages + response = ( + memorystore.ListInstancesResponse( + instances=[ + memorystore.Instance(), + memorystore.Instance(), + memorystore.Instance(), + ], + next_page_token="abc", + ), + memorystore.ListInstancesResponse( + instances=[], + next_page_token="def", + ), + memorystore.ListInstancesResponse( + instances=[ + memorystore.Instance(), + ], + next_page_token="ghi", + ), + memorystore.ListInstancesResponse( + instances=[ + memorystore.Instance(), + memorystore.Instance(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(memorystore.ListInstancesResponse.to_json(x) for x in response) + return_values = tuple(Response() for i in response) + for return_val, response_val in zip(return_values, response): + return_val._content = response_val.encode("UTF-8") + return_val.status_code = 200 + req.side_effect = return_values + + sample_request = {"parent": "projects/sample1/locations/sample2"} + + pager = client.list_instances(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, memorystore.Instance) for i in results) + + pages = list(client.list_instances(request=sample_request).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +def test_get_instance_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = MemorystoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_instance in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.get_instance] = mock_rpc + + request = {} + client.get_instance(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_instance(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_get_instance_rest_required_fields(request_type=memorystore.GetInstanceRequest): + transport_class = transports.MemorystoreRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get_instance._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get_instance._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + + client = MemorystoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = memorystore.Instance() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "get", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = memorystore.Instance.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.get_instance(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_get_instance_rest_unset_required_fields(): + transport = transports.MemorystoreRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.get_instance._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) + + +def test_get_instance_rest_flattened(): + client = MemorystoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = memorystore.Instance() + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/instances/sample3" + } + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = memorystore.Instance.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.get_instance(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1/{name=projects/*/locations/*/instances/*}" % client.transport._host, + args[1], + ) + + +def test_get_instance_rest_flattened_error(transport: str = "rest"): + client = MemorystoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_instance( + memorystore.GetInstanceRequest(), + name="name_value", + ) + + +def test_create_instance_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = MemorystoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.create_instance in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.create_instance] = mock_rpc + + request = {} + client.create_instance(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.create_instance(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_create_instance_rest_required_fields( + request_type=memorystore.CreateInstanceRequest, +): + transport_class = transports.MemorystoreRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["instance_id"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + assert "instanceId" not in jsonified_request + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).create_instance._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + assert "instanceId" in jsonified_request + assert jsonified_request["instanceId"] == request_init["instance_id"] + + jsonified_request["parent"] = "parent_value" + jsonified_request["instanceId"] = "instance_id_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).create_instance._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "instance_id", + "request_id", + ) + ) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + assert "instanceId" in jsonified_request + assert jsonified_request["instanceId"] == "instance_id_value" + + client = MemorystoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "post", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.create_instance(request) + + expected_params = [ + ( + "instanceId", + "", + ), + ("$alt", "json;enum-encoding=int"), + ] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_create_instance_rest_unset_required_fields(): + transport = transports.MemorystoreRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.create_instance._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "instanceId", + "requestId", + ) + ) + & set( + ( + "parent", + "instanceId", + "instance", + ) + ) + ) + + +def test_create_instance_rest_flattened(): + client = MemorystoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = memorystore.ListInstancesResponse() + return_value = operations_pb2.Operation(name="operations/spam") # get arguments that satisfy an http rule for this method sample_request = {"parent": "projects/sample1/locations/sample2"} @@ -7222,20 +8263,22 @@ def test_list_instances_rest_flattened(): # get truthy value for each flattened field mock_args = dict( parent="parent_value", + instance=memorystore.Instance( + gcs_source=memorystore.Instance.GcsBackupSource(uris=["uris_value"]) + ), + instance_id="instance_id_value", ) mock_args.update(sample_request) # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 - # Convert return value to protobuf type - return_value = memorystore.ListInstancesResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.list_instances(**mock_args) + client.create_instance(**mock_args) # Establish that the underlying call was made with the expected # request object values. @@ -7247,7 +8290,7 @@ def test_list_instances_rest_flattened(): ) -def test_list_instances_rest_flattened_error(transport: str = "rest"): +def test_create_instance_rest_flattened_error(transport: str = "rest"): client = MemorystoreClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -7256,74 +8299,17 @@ def test_list_instances_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_instances( - memorystore.ListInstancesRequest(), + client.create_instance( + memorystore.CreateInstanceRequest(), parent="parent_value", - ) - - -def test_list_instances_rest_pager(transport: str = "rest"): - client = MemorystoreClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, "request") as req: - # TODO(kbandes): remove this mock unless there's a good reason for it. - # with mock.patch.object(path_template, 'transcode') as transcode: - # Set the response as a series of pages - response = ( - memorystore.ListInstancesResponse( - instances=[ - memorystore.Instance(), - memorystore.Instance(), - memorystore.Instance(), - ], - next_page_token="abc", - ), - memorystore.ListInstancesResponse( - instances=[], - next_page_token="def", - ), - memorystore.ListInstancesResponse( - instances=[ - memorystore.Instance(), - ], - next_page_token="ghi", - ), - memorystore.ListInstancesResponse( - instances=[ - memorystore.Instance(), - memorystore.Instance(), - ], + instance=memorystore.Instance( + gcs_source=memorystore.Instance.GcsBackupSource(uris=["uris_value"]) ), + instance_id="instance_id_value", ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(memorystore.ListInstancesResponse.to_json(x) for x in response) - return_values = tuple(Response() for i in response) - for return_val, response_val in zip(return_values, response): - return_val._content = response_val.encode("UTF-8") - return_val.status_code = 200 - req.side_effect = return_values - - sample_request = {"parent": "projects/sample1/locations/sample2"} - - pager = client.list_instances(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, memorystore.Instance) for i in results) - - pages = list(client.list_instances(request=sample_request).pages) - for page_, token in zip(pages, ["abc", "def", "ghi", ""]): - assert page_.raw_page.next_page_token == token -def test_get_instance_rest_use_cached_wrapped_rpc(): +def test_update_instance_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -7337,33 +8323,38 @@ def test_get_instance_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.get_instance in client._transport._wrapped_methods + assert client._transport.update_instance in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.Mock() mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.get_instance] = mock_rpc + client._transport._wrapped_methods[client._transport.update_instance] = mock_rpc request = {} - client.get_instance(request) + client.update_instance(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.get_instance(request) + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.update_instance(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_get_instance_rest_required_fields(request_type=memorystore.GetInstanceRequest): +def test_update_instance_rest_required_fields( + request_type=memorystore.UpdateInstanceRequest, +): transport_class = transports.MemorystoreRestTransport request_init = {} - request_init["name"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -7374,21 +8365,24 @@ def test_get_instance_rest_required_fields(request_type=memorystore.GetInstanceR unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).get_instance._get_unset_required_fields(jsonified_request) + ).update_instance._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present - jsonified_request["name"] = "name_value" - unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).get_instance._get_unset_required_fields(jsonified_request) + ).update_instance._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "request_id", + "update_mask", + ) + ) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == "name_value" client = MemorystoreClient( credentials=ga_credentials.AnonymousCredentials(), @@ -7397,7 +8391,7 @@ def test_get_instance_rest_required_fields(request_type=memorystore.GetInstanceR request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = memorystore.Instance() + return_value = operations_pb2.Operation(name="operations/spam") # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values @@ -7409,39 +8403,45 @@ def test_get_instance_rest_required_fields(request_type=memorystore.GetInstanceR pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "get", + "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 = memorystore.Instance.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.get_instance(request) + response = client.update_instance(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert sorted(expected_params) == sorted(actual_params) -def test_get_instance_rest_unset_required_fields(): +def test_update_instance_rest_unset_required_fields(): transport = transports.MemorystoreRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.get_instance._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name",))) + unset_fields = transport.update_instance._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "requestId", + "updateMask", + ) + ) + & set(("instance",)) + ) + - -def test_get_instance_rest_flattened(): +def test_update_instance_rest_flattened(): client = MemorystoreClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -7450,42 +8450,44 @@ def test_get_instance_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 = memorystore.Instance() + return_value = operations_pb2.Operation(name="operations/spam") # get arguments that satisfy an http rule for this method sample_request = { - "name": "projects/sample1/locations/sample2/instances/sample3" + "instance": {"name": "projects/sample1/locations/sample2/instances/sample3"} } # get truthy value for each flattened field mock_args = dict( - name="name_value", + instance=memorystore.Instance( + gcs_source=memorystore.Instance.GcsBackupSource(uris=["uris_value"]) + ), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) mock_args.update(sample_request) # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 - # Convert return value to protobuf type - return_value = memorystore.Instance.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.get_instance(**mock_args) + client.update_instance(**mock_args) # Establish that the underlying call was made with the expected # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] assert path_template.validate( - "%s/v1/{name=projects/*/locations/*/instances/*}" % client.transport._host, + "%s/v1/{instance.name=projects/*/locations/*/instances/*}" + % client.transport._host, args[1], ) -def test_get_instance_rest_flattened_error(transport: str = "rest"): +def test_update_instance_rest_flattened_error(transport: str = "rest"): client = MemorystoreClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -7494,13 +8496,16 @@ def test_get_instance_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_instance( - memorystore.GetInstanceRequest(), - name="name_value", + client.update_instance( + memorystore.UpdateInstanceRequest(), + instance=memorystore.Instance( + gcs_source=memorystore.Instance.GcsBackupSource(uris=["uris_value"]) + ), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) -def test_create_instance_rest_use_cached_wrapped_rpc(): +def test_delete_instance_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -7514,17 +8519,17 @@ def test_create_instance_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.create_instance in client._transport._wrapped_methods + assert client._transport.delete_instance in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.Mock() mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.create_instance] = mock_rpc + client._transport._wrapped_methods[client._transport.delete_instance] = mock_rpc request = {} - client.create_instance(request) + client.delete_instance(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 @@ -7533,21 +8538,20 @@ def test_create_instance_rest_use_cached_wrapped_rpc(): # subsequent calls should use the cached wrapper wrapper_fn.reset_mock() - client.create_instance(request) + client.delete_instance(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_create_instance_rest_required_fields( - request_type=memorystore.CreateInstanceRequest, +def test_delete_instance_rest_required_fields( + request_type=memorystore.DeleteInstanceRequest, ): transport_class = transports.MemorystoreRestTransport request_init = {} - request_init["parent"] = "" - request_init["instance_id"] = "" + request_init["name"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -7555,37 +8559,26 @@ def test_create_instance_rest_required_fields( ) # verify fields with default values are dropped - assert "instanceId" not in jsonified_request unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).create_instance._get_unset_required_fields(jsonified_request) + ).delete_instance._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present - assert "instanceId" in jsonified_request - assert jsonified_request["instanceId"] == request_init["instance_id"] - jsonified_request["parent"] = "parent_value" - jsonified_request["instanceId"] = "instance_id_value" + jsonified_request["name"] = "name_value" unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).create_instance._get_unset_required_fields(jsonified_request) + ).delete_instance._get_unset_required_fields(jsonified_request) # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set( - ( - "instance_id", - "request_id", - ) - ) + 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" - assert "instanceId" in jsonified_request - assert jsonified_request["instanceId"] == "instance_id_value" + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" client = MemorystoreClient( credentials=ga_credentials.AnonymousCredentials(), @@ -7606,10 +8599,9 @@ def test_create_instance_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() @@ -7620,43 +8612,23 @@ def test_create_instance_rest_required_fields( req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.create_instance(request) + response = client.delete_instance(request) - expected_params = [ - ( - "instanceId", - "", - ), - ("$alt", "json;enum-encoding=int"), - ] + expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert sorted(expected_params) == sorted(actual_params) -def test_create_instance_rest_unset_required_fields(): +def test_delete_instance_rest_unset_required_fields(): transport = transports.MemorystoreRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.create_instance._get_unset_required_fields({}) - assert set(unset_fields) == ( - set( - ( - "instanceId", - "requestId", - ) - ) - & set( - ( - "parent", - "instanceId", - "instance", - ) - ) - ) + unset_fields = transport.delete_instance._get_unset_required_fields({}) + assert set(unset_fields) == (set(("requestId",)) & set(("name",))) -def test_create_instance_rest_flattened(): +def test_delete_instance_rest_flattened(): client = MemorystoreClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -7668,15 +8640,13 @@ def test_create_instance_rest_flattened(): return_value = operations_pb2.Operation(name="operations/spam") # get arguments that satisfy an http rule for this method - sample_request = {"parent": "projects/sample1/locations/sample2"} + sample_request = { + "name": "projects/sample1/locations/sample2/instances/sample3" + } # get truthy value for each flattened field mock_args = dict( - parent="parent_value", - instance=memorystore.Instance( - gcs_source=memorystore.Instance.GcsBackupSource(uris=["uris_value"]) - ), - instance_id="instance_id_value", + name="name_value", ) mock_args.update(sample_request) @@ -7688,19 +8658,19 @@ def test_create_instance_rest_flattened(): req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.create_instance(**mock_args) + client.delete_instance(**mock_args) # Establish that the underlying call was made with the expected # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] assert path_template.validate( - "%s/v1/{parent=projects/*/locations/*}/instances" % client.transport._host, + "%s/v1/{name=projects/*/locations/*/instances/*}" % client.transport._host, args[1], ) -def test_create_instance_rest_flattened_error(transport: str = "rest"): +def test_delete_instance_rest_flattened_error(transport: str = "rest"): client = MemorystoreClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -7709,17 +8679,13 @@ def test_create_instance_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_instance( - memorystore.CreateInstanceRequest(), - parent="parent_value", - instance=memorystore.Instance( - gcs_source=memorystore.Instance.GcsBackupSource(uris=["uris_value"]) - ), - instance_id="instance_id_value", + client.delete_instance( + memorystore.DeleteInstanceRequest(), + name="name_value", ) -def test_update_instance_rest_use_cached_wrapped_rpc(): +def test_get_certificate_authority_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -7733,38 +8699,40 @@ def test_update_instance_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.update_instance in client._transport._wrapped_methods + assert ( + client._transport.get_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.update_instance] = mock_rpc + client._transport._wrapped_methods[ + client._transport.get_certificate_authority + ] = mock_rpc request = {} - client.update_instance(request) + client.get_certificate_authority(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - # Operation methods build a cached wrapper on first rpc call - # subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() - - client.update_instance(request) + client.get_certificate_authority(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_update_instance_rest_required_fields( - request_type=memorystore.UpdateInstanceRequest, +def test_get_certificate_authority_rest_required_fields( + request_type=memorystore.GetCertificateAuthorityRequest, ): transport_class = transports.MemorystoreRestTransport request_init = {} + request_init["name"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -7775,24 +8743,21 @@ def test_update_instance_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).update_instance._get_unset_required_fields(jsonified_request) + ).get_certificate_authority._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present + jsonified_request["name"] = "name_value" + unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).update_instance._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set( - ( - "request_id", - "update_mask", - ) - ) + ).get_certificate_authority._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" client = MemorystoreClient( credentials=ga_credentials.AnonymousCredentials(), @@ -7801,7 +8766,7 @@ def test_update_instance_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name="operations/spam") + return_value = memorystore.CertificateAuthority() # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values @@ -7813,45 +8778,39 @@ def test_update_instance_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 = memorystore.CertificateAuthority.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.update_instance(request) + response = client.get_certificate_authority(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert sorted(expected_params) == sorted(actual_params) -def test_update_instance_rest_unset_required_fields(): +def test_get_certificate_authority_rest_unset_required_fields(): transport = transports.MemorystoreRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.update_instance._get_unset_required_fields({}) - assert set(unset_fields) == ( - set( - ( - "requestId", - "updateMask", - ) - ) - & set(("instance",)) - ) + unset_fields = transport.get_certificate_authority._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) -def test_update_instance_rest_flattened(): +def test_get_certificate_authority_rest_flattened(): client = MemorystoreClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -7860,44 +8819,43 @@ def test_update_instance_rest_flattened(): # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name="operations/spam") + return_value = memorystore.CertificateAuthority() # get arguments that satisfy an http rule for this method sample_request = { - "instance": {"name": "projects/sample1/locations/sample2/instances/sample3"} + "name": "projects/sample1/locations/sample2/instances/sample3" } # get truthy value for each flattened field mock_args = dict( - instance=memorystore.Instance( - gcs_source=memorystore.Instance.GcsBackupSource(uris=["uris_value"]) - ), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + name="name_value", ) mock_args.update(sample_request) # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 + # Convert return value to protobuf type + return_value = memorystore.CertificateAuthority.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.update_instance(**mock_args) + client.get_certificate_authority(**mock_args) # Establish that the underlying call was made with the expected # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] assert path_template.validate( - "%s/v1/{instance.name=projects/*/locations/*/instances/*}" + "%s/v1/{name=projects/*/locations/*/instances/*}/certificateAuthority" % client.transport._host, args[1], ) -def test_update_instance_rest_flattened_error(transport: str = "rest"): +def test_get_certificate_authority_rest_flattened_error(transport: str = "rest"): client = MemorystoreClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -7906,16 +8864,13 @@ def test_update_instance_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_instance( - memorystore.UpdateInstanceRequest(), - instance=memorystore.Instance( - gcs_source=memorystore.Instance.GcsBackupSource(uris=["uris_value"]) - ), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + client.get_certificate_authority( + memorystore.GetCertificateAuthorityRequest(), + name="name_value", ) -def test_delete_instance_rest_use_cached_wrapped_rpc(): +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: @@ -7929,34 +8884,35 @@ def test_delete_instance_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.delete_instance in client._transport._wrapped_methods + 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.delete_instance] = mock_rpc + client._transport._wrapped_methods[ + client._transport.get_shared_regional_certificate_authority + ] = mock_rpc request = {} - client.delete_instance(request) + client.get_shared_regional_certificate_authority(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - # Operation methods build a cached wrapper on first rpc call - # subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() - - client.delete_instance(request) + 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_delete_instance_rest_required_fields( - request_type=memorystore.DeleteInstanceRequest, +def test_get_shared_regional_certificate_authority_rest_required_fields( + request_type=memorystore.GetSharedRegionalCertificateAuthorityRequest, ): transport_class = transports.MemorystoreRestTransport @@ -7972,18 +8928,20 @@ def test_delete_instance_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).delete_instance._get_unset_required_fields(jsonified_request) + ).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() - ).delete_instance._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("request_id",)) + 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 @@ -7997,7 +8955,7 @@ def test_delete_instance_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name="operations/spam") + return_value = 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 @@ -8009,36 +8967,45 @@ def test_delete_instance_rest_required_fields( pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "delete", + "method": "get", "query_params": pb_request, } transcode.return_value = transcode_result response_value = Response() response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = 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.delete_instance(request) + response = client.get_shared_regional_certificate_authority(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert sorted(expected_params) == sorted(actual_params) -def test_delete_instance_rest_unset_required_fields(): +def test_get_shared_regional_certificate_authority_rest_unset_required_fields(): transport = transports.MemorystoreRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.delete_instance._get_unset_required_fields({}) - assert set(unset_fields) == (set(("requestId",)) & set(("name",))) + unset_fields = ( + transport.get_shared_regional_certificate_authority._get_unset_required_fields( + {} + ) + ) + assert set(unset_fields) == (set(()) & set(("name",))) -def test_delete_instance_rest_flattened(): +def test_get_shared_regional_certificate_authority_rest_flattened(): client = MemorystoreClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -8047,11 +9014,11 @@ def test_delete_instance_rest_flattened(): # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name="operations/spam") + return_value = memorystore.SharedRegionalCertificateAuthority() # get arguments that satisfy an http rule for this method sample_request = { - "name": "projects/sample1/locations/sample2/instances/sample3" + "name": "projects/sample1/locations/sample2/sharedRegionalCertificateAuthority" } # get truthy value for each flattened field @@ -8063,24 +9030,29 @@ def test_delete_instance_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 = 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.delete_instance(**mock_args) + 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/v1/{name=projects/*/locations/*/instances/*}" % client.transport._host, + "%s/v1/{name=projects/*/locations/*/sharedRegionalCertificateAuthority}" + % client.transport._host, args[1], ) -def test_delete_instance_rest_flattened_error(transport: str = "rest"): +def test_get_shared_regional_certificate_authority_rest_flattened_error( + transport: str = "rest", +): client = MemorystoreClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -8089,13 +9061,13 @@ def test_delete_instance_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_instance( - memorystore.DeleteInstanceRequest(), + client.get_shared_regional_certificate_authority( + memorystore.GetSharedRegionalCertificateAuthorityRequest(), name="name_value", ) -def test_get_certificate_authority_rest_use_cached_wrapped_rpc(): +def test_reschedule_maintenance_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -8110,7 +9082,7 @@ def test_get_certificate_authority_rest_use_cached_wrapped_rpc(): # Ensure method has been cached assert ( - client._transport.get_certificate_authority + client._transport.reschedule_maintenance in client._transport._wrapped_methods ) @@ -8119,25 +9091,29 @@ def test_get_certificate_authority_rest_use_cached_wrapped_rpc(): mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[ - client._transport.get_certificate_authority - ] = mock_rpc + client._transport._wrapped_methods[client._transport.reschedule_maintenance] = ( + mock_rpc + ) request = {} - client.get_certificate_authority(request) + client.reschedule_maintenance(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.get_certificate_authority(request) + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.reschedule_maintenance(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_get_certificate_authority_rest_required_fields( - request_type=memorystore.GetCertificateAuthorityRequest, +def test_reschedule_maintenance_rest_required_fields( + request_type=memorystore.RescheduleMaintenanceRequest, ): transport_class = transports.MemorystoreRestTransport @@ -8153,7 +9129,7 @@ def test_get_certificate_authority_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).get_certificate_authority._get_unset_required_fields(jsonified_request) + ).reschedule_maintenance._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present @@ -8162,7 +9138,7 @@ def test_get_certificate_authority_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).get_certificate_authority._get_unset_required_fields(jsonified_request) + ).reschedule_maintenance._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone @@ -8176,7 +9152,7 @@ def test_get_certificate_authority_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = memorystore.CertificateAuthority() + return_value = operations_pb2.Operation(name="operations/spam") # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values @@ -8188,39 +9164,45 @@ def test_get_certificate_authority_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 = memorystore.CertificateAuthority.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.get_certificate_authority(request) + response = client.reschedule_maintenance(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert sorted(expected_params) == sorted(actual_params) -def test_get_certificate_authority_rest_unset_required_fields(): +def test_reschedule_maintenance_rest_unset_required_fields(): transport = transports.MemorystoreRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.get_certificate_authority._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name",))) + unset_fields = transport.reschedule_maintenance._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(()) + & set( + ( + "name", + "rescheduleType", + ) + ) + ) -def test_get_certificate_authority_rest_flattened(): +def test_reschedule_maintenance_rest_flattened(): client = MemorystoreClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -8229,7 +9211,7 @@ def test_get_certificate_authority_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 = memorystore.CertificateAuthority() + return_value = operations_pb2.Operation(name="operations/spam") # get arguments that satisfy an http rule for this method sample_request = { @@ -8239,33 +9221,33 @@ def test_get_certificate_authority_rest_flattened(): # get truthy value for each flattened field mock_args = dict( name="name_value", + reschedule_type=memorystore.RescheduleMaintenanceRequest.RescheduleType.IMMEDIATE, + schedule_time=timestamp_pb2.Timestamp(seconds=751), ) mock_args.update(sample_request) # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 - # Convert return value to protobuf type - return_value = memorystore.CertificateAuthority.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.get_certificate_authority(**mock_args) + client.reschedule_maintenance(**mock_args) # Establish that the underlying call was made with the expected # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] assert path_template.validate( - "%s/v1/{name=projects/*/locations/*/instances/*}/certificateAuthority" + "%s/v1/{name=projects/*/locations/*/instances/*}:rescheduleMaintenance" % client.transport._host, args[1], ) -def test_get_certificate_authority_rest_flattened_error(transport: str = "rest"): +def test_reschedule_maintenance_rest_flattened_error(transport: str = "rest"): client = MemorystoreClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -8274,13 +9256,15 @@ def test_get_certificate_authority_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_certificate_authority( - memorystore.GetCertificateAuthorityRequest(), + client.reschedule_maintenance( + memorystore.RescheduleMaintenanceRequest(), name="name_value", + reschedule_type=memorystore.RescheduleMaintenanceRequest.RescheduleType.IMMEDIATE, + schedule_time=timestamp_pb2.Timestamp(seconds=751), ) -def test_get_shared_regional_certificate_authority_rest_use_cached_wrapped_rpc(): +def test_list_backup_collections_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -8295,7 +9279,7 @@ def test_get_shared_regional_certificate_authority_rest_use_cached_wrapped_rpc() # Ensure method has been cached assert ( - client._transport.get_shared_regional_certificate_authority + client._transport.list_backup_collections in client._transport._wrapped_methods ) @@ -8305,29 +9289,29 @@ def test_get_shared_regional_certificate_authority_rest_use_cached_wrapped_rpc() "foo" # operation_request.operation in compute client(s) expect a string. ) client._transport._wrapped_methods[ - client._transport.get_shared_regional_certificate_authority + client._transport.list_backup_collections ] = mock_rpc request = {} - client.get_shared_regional_certificate_authority(request) + client.list_backup_collections(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.get_shared_regional_certificate_authority(request) + client.list_backup_collections(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_get_shared_regional_certificate_authority_rest_required_fields( - request_type=memorystore.GetSharedRegionalCertificateAuthorityRequest, +def test_list_backup_collections_rest_required_fields( + request_type=memorystore.ListBackupCollectionsRequest, ): transport_class = transports.MemorystoreRestTransport request_init = {} - request_init["name"] = "" + request_init["parent"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -8338,25 +9322,28 @@ def test_get_shared_regional_certificate_authority_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).get_shared_regional_certificate_authority._get_unset_required_fields( - jsonified_request - ) + ).list_backup_collections._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present - jsonified_request["name"] = "name_value" + jsonified_request["parent"] = "parent_value" unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).get_shared_regional_certificate_authority._get_unset_required_fields( - jsonified_request + ).list_backup_collections._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "page_size", + "page_token", + ) ) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == "name_value" + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" client = MemorystoreClient( credentials=ga_credentials.AnonymousCredentials(), @@ -8365,7 +9352,7 @@ def test_get_shared_regional_certificate_authority_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = memorystore.SharedRegionalCertificateAuthority() + return_value = memorystore.ListBackupCollectionsResponse() # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values @@ -8386,36 +9373,38 @@ def test_get_shared_regional_certificate_authority_rest_required_fields( response_value.status_code = 200 # Convert return value to protobuf type - return_value = memorystore.SharedRegionalCertificateAuthority.pb( - return_value - ) + return_value = memorystore.ListBackupCollectionsResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.get_shared_regional_certificate_authority(request) + response = client.list_backup_collections(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert sorted(expected_params) == sorted(actual_params) -def test_get_shared_regional_certificate_authority_rest_unset_required_fields(): +def test_list_backup_collections_rest_unset_required_fields(): transport = transports.MemorystoreRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = ( - transport.get_shared_regional_certificate_authority._get_unset_required_fields( - {} + unset_fields = transport.list_backup_collections._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "pageSize", + "pageToken", + ) ) + & set(("parent",)) ) - assert set(unset_fields) == (set(()) & set(("name",))) -def test_get_shared_regional_certificate_authority_rest_flattened(): +def test_list_backup_collections_rest_flattened(): client = MemorystoreClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -8424,16 +9413,14 @@ def test_get_shared_regional_certificate_authority_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 = memorystore.SharedRegionalCertificateAuthority() + return_value = memorystore.ListBackupCollectionsResponse() # get arguments that satisfy an http rule for this method - sample_request = { - "name": "projects/sample1/locations/sample2/sharedRegionalCertificateAuthority" - } + sample_request = {"parent": "projects/sample1/locations/sample2"} # get truthy value for each flattened field mock_args = dict( - name="name_value", + parent="parent_value", ) mock_args.update(sample_request) @@ -8441,43 +9428,104 @@ def test_get_shared_regional_certificate_authority_rest_flattened(): response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = memorystore.SharedRegionalCertificateAuthority.pb(return_value) + return_value = memorystore.ListBackupCollectionsResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.get_shared_regional_certificate_authority(**mock_args) + client.list_backup_collections(**mock_args) # Establish that the underlying call was made with the expected # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] assert path_template.validate( - "%s/v1/{name=projects/*/locations/*/sharedRegionalCertificateAuthority}" + "%s/v1/{parent=projects/*/locations/*}/backupCollections" % client.transport._host, args[1], ) -def test_get_shared_regional_certificate_authority_rest_flattened_error( - transport: str = "rest", -): +def test_list_backup_collections_rest_flattened_error(transport: str = "rest"): + client = MemorystoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_backup_collections( + memorystore.ListBackupCollectionsRequest(), + parent="parent_value", + ) + + +def test_list_backup_collections_rest_pager(transport: str = "rest"): client = MemorystoreClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) - # 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", - ) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # TODO(kbandes): remove this mock unless there's a good reason for it. + # with mock.patch.object(path_template, 'transcode') as transcode: + # Set the response as a series of pages + response = ( + memorystore.ListBackupCollectionsResponse( + backup_collections=[ + memorystore.BackupCollection(), + memorystore.BackupCollection(), + memorystore.BackupCollection(), + ], + next_page_token="abc", + ), + memorystore.ListBackupCollectionsResponse( + backup_collections=[], + next_page_token="def", + ), + memorystore.ListBackupCollectionsResponse( + backup_collections=[ + memorystore.BackupCollection(), + ], + next_page_token="ghi", + ), + memorystore.ListBackupCollectionsResponse( + backup_collections=[ + memorystore.BackupCollection(), + memorystore.BackupCollection(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple( + memorystore.ListBackupCollectionsResponse.to_json(x) for x in response + ) + return_values = tuple(Response() for i in response) + for return_val, response_val in zip(return_values, response): + return_val._content = response_val.encode("UTF-8") + return_val.status_code = 200 + req.side_effect = return_values + + sample_request = {"parent": "projects/sample1/locations/sample2"} + + pager = client.list_backup_collections(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, memorystore.BackupCollection) for i in results) + + pages = list(client.list_backup_collections(request=sample_request).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token -def test_reschedule_maintenance_rest_use_cached_wrapped_rpc(): +def test_get_backup_collection_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -8492,7 +9540,7 @@ def test_reschedule_maintenance_rest_use_cached_wrapped_rpc(): # Ensure method has been cached assert ( - client._transport.reschedule_maintenance + client._transport.get_backup_collection in client._transport._wrapped_methods ) @@ -8501,29 +9549,25 @@ def test_reschedule_maintenance_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.reschedule_maintenance] = ( + client._transport._wrapped_methods[client._transport.get_backup_collection] = ( mock_rpc ) request = {} - client.reschedule_maintenance(request) + client.get_backup_collection(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - # Operation methods build a cached wrapper on first rpc call - # subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() - - client.reschedule_maintenance(request) + client.get_backup_collection(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_reschedule_maintenance_rest_required_fields( - request_type=memorystore.RescheduleMaintenanceRequest, +def test_get_backup_collection_rest_required_fields( + request_type=memorystore.GetBackupCollectionRequest, ): transport_class = transports.MemorystoreRestTransport @@ -8539,7 +9583,7 @@ def test_reschedule_maintenance_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).reschedule_maintenance._get_unset_required_fields(jsonified_request) + ).get_backup_collection._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present @@ -8548,7 +9592,7 @@ def test_reschedule_maintenance_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).reschedule_maintenance._get_unset_required_fields(jsonified_request) + ).get_backup_collection._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone @@ -8562,7 +9606,7 @@ def test_reschedule_maintenance_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name="operations/spam") + return_value = memorystore.BackupCollection() # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values @@ -8574,45 +9618,39 @@ def test_reschedule_maintenance_rest_required_fields( pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "post", + "method": "get", "query_params": pb_request, } - transcode_result["body"] = pb_request transcode.return_value = transcode_result response_value = Response() response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = memorystore.BackupCollection.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.reschedule_maintenance(request) + response = client.get_backup_collection(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert sorted(expected_params) == sorted(actual_params) -def test_reschedule_maintenance_rest_unset_required_fields(): +def test_get_backup_collection_rest_unset_required_fields(): transport = transports.MemorystoreRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.reschedule_maintenance._get_unset_required_fields({}) - assert set(unset_fields) == ( - set(()) - & set( - ( - "name", - "rescheduleType", - ) - ) - ) + unset_fields = transport.get_backup_collection._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) -def test_reschedule_maintenance_rest_flattened(): +def test_get_backup_collection_rest_flattened(): client = MemorystoreClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -8621,43 +9659,43 @@ def test_reschedule_maintenance_rest_flattened(): # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name="operations/spam") + return_value = memorystore.BackupCollection() # get arguments that satisfy an http rule for this method sample_request = { - "name": "projects/sample1/locations/sample2/instances/sample3" + "name": "projects/sample1/locations/sample2/backupCollections/sample3" } # get truthy value for each flattened field mock_args = dict( name="name_value", - reschedule_type=memorystore.RescheduleMaintenanceRequest.RescheduleType.IMMEDIATE, - schedule_time=timestamp_pb2.Timestamp(seconds=751), ) mock_args.update(sample_request) # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 + # Convert return value to protobuf type + return_value = memorystore.BackupCollection.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.reschedule_maintenance(**mock_args) + client.get_backup_collection(**mock_args) # Establish that the underlying call was made with the expected # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] assert path_template.validate( - "%s/v1/{name=projects/*/locations/*/instances/*}:rescheduleMaintenance" + "%s/v1/{name=projects/*/locations/*/backupCollections/*}" % client.transport._host, args[1], ) -def test_reschedule_maintenance_rest_flattened_error(transport: str = "rest"): +def test_get_backup_collection_rest_flattened_error(transport: str = "rest"): client = MemorystoreClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -8666,15 +9704,13 @@ def test_reschedule_maintenance_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.reschedule_maintenance( - memorystore.RescheduleMaintenanceRequest(), + client.get_backup_collection( + memorystore.GetBackupCollectionRequest(), name="name_value", - reschedule_type=memorystore.RescheduleMaintenanceRequest.RescheduleType.IMMEDIATE, - schedule_time=timestamp_pb2.Timestamp(seconds=751), ) -def test_list_backup_collections_rest_use_cached_wrapped_rpc(): +def test_list_backups_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -8688,36 +9724,29 @@ def test_list_backup_collections_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert ( - client._transport.list_backup_collections - in client._transport._wrapped_methods - ) + assert client._transport.list_backups in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.Mock() mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[ - client._transport.list_backup_collections - ] = mock_rpc + client._transport._wrapped_methods[client._transport.list_backups] = mock_rpc request = {} - client.list_backup_collections(request) + client.list_backups(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.list_backup_collections(request) + client.list_backups(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_list_backup_collections_rest_required_fields( - request_type=memorystore.ListBackupCollectionsRequest, -): +def test_list_backups_rest_required_fields(request_type=memorystore.ListBackupsRequest): transport_class = transports.MemorystoreRestTransport request_init = {} @@ -8732,7 +9761,7 @@ def test_list_backup_collections_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).list_backup_collections._get_unset_required_fields(jsonified_request) + ).list_backups._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present @@ -8741,7 +9770,7 @@ def test_list_backup_collections_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).list_backup_collections._get_unset_required_fields(jsonified_request) + ).list_backups._get_unset_required_fields(jsonified_request) # Check that path parameters and body parameters are not mixing in. assert not set(unset_fields) - set( ( @@ -8762,7 +9791,7 @@ def test_list_backup_collections_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = memorystore.ListBackupCollectionsResponse() + return_value = memorystore.ListBackupsResponse() # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values @@ -8783,26 +9812,26 @@ def test_list_backup_collections_rest_required_fields( response_value.status_code = 200 # Convert return value to protobuf type - return_value = memorystore.ListBackupCollectionsResponse.pb(return_value) + return_value = memorystore.ListBackupsResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.list_backup_collections(request) + response = client.list_backups(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert sorted(expected_params) == sorted(actual_params) -def test_list_backup_collections_rest_unset_required_fields(): +def test_list_backups_rest_unset_required_fields(): transport = transports.MemorystoreRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.list_backup_collections._get_unset_required_fields({}) + unset_fields = transport.list_backups._get_unset_required_fields({}) assert set(unset_fields) == ( set( ( @@ -8814,7 +9843,7 @@ def test_list_backup_collections_rest_unset_required_fields(): ) -def test_list_backup_collections_rest_flattened(): +def test_list_backups_rest_flattened(): client = MemorystoreClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -8823,10 +9852,12 @@ def test_list_backup_collections_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 = memorystore.ListBackupCollectionsResponse() + return_value = memorystore.ListBackupsResponse() # get arguments that satisfy an http rule for this method - sample_request = {"parent": "projects/sample1/locations/sample2"} + sample_request = { + "parent": "projects/sample1/locations/sample2/backupCollections/sample3" + } # get truthy value for each flattened field mock_args = dict( @@ -8838,26 +9869,26 @@ def test_list_backup_collections_rest_flattened(): response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = memorystore.ListBackupCollectionsResponse.pb(return_value) + return_value = memorystore.ListBackupsResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.list_backup_collections(**mock_args) + client.list_backups(**mock_args) # Establish that the underlying call was made with the expected # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] assert path_template.validate( - "%s/v1/{parent=projects/*/locations/*}/backupCollections" + "%s/v1/{parent=projects/*/locations/*/backupCollections/*}/backups" % client.transport._host, args[1], ) -def test_list_backup_collections_rest_flattened_error(transport: str = "rest"): +def test_list_backups_rest_flattened_error(transport: str = "rest"): client = MemorystoreClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -8866,13 +9897,13 @@ def test_list_backup_collections_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_backup_collections( - memorystore.ListBackupCollectionsRequest(), + client.list_backups( + memorystore.ListBackupsRequest(), parent="parent_value", ) -def test_list_backup_collections_rest_pager(transport: str = "rest"): +def test_list_backups_rest_pager(transport: str = "rest"): client = MemorystoreClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -8884,28 +9915,28 @@ def test_list_backup_collections_rest_pager(transport: str = "rest"): # with mock.patch.object(path_template, 'transcode') as transcode: # Set the response as a series of pages response = ( - memorystore.ListBackupCollectionsResponse( - backup_collections=[ - memorystore.BackupCollection(), - memorystore.BackupCollection(), - memorystore.BackupCollection(), + memorystore.ListBackupsResponse( + backups=[ + memorystore.Backup(), + memorystore.Backup(), + memorystore.Backup(), ], next_page_token="abc", ), - memorystore.ListBackupCollectionsResponse( - backup_collections=[], + memorystore.ListBackupsResponse( + backups=[], next_page_token="def", ), - memorystore.ListBackupCollectionsResponse( - backup_collections=[ - memorystore.BackupCollection(), + memorystore.ListBackupsResponse( + backups=[ + memorystore.Backup(), ], next_page_token="ghi", ), - memorystore.ListBackupCollectionsResponse( - backup_collections=[ - memorystore.BackupCollection(), - memorystore.BackupCollection(), + memorystore.ListBackupsResponse( + backups=[ + memorystore.Backup(), + memorystore.Backup(), ], ), ) @@ -8913,29 +9944,29 @@ def test_list_backup_collections_rest_pager(transport: str = "rest"): response = response + response # Wrap the values into proper Response objs - response = tuple( - memorystore.ListBackupCollectionsResponse.to_json(x) for x in response - ) + response = tuple(memorystore.ListBackupsResponse.to_json(x) for x in response) return_values = tuple(Response() for i in response) for return_val, response_val in zip(return_values, response): return_val._content = response_val.encode("UTF-8") return_val.status_code = 200 req.side_effect = return_values - sample_request = {"parent": "projects/sample1/locations/sample2"} + sample_request = { + "parent": "projects/sample1/locations/sample2/backupCollections/sample3" + } - pager = client.list_backup_collections(request=sample_request) + pager = client.list_backups(request=sample_request) results = list(pager) assert len(results) == 6 - assert all(isinstance(i, memorystore.BackupCollection) for i in results) + assert all(isinstance(i, memorystore.Backup) for i in results) - pages = list(client.list_backup_collections(request=sample_request).pages) + pages = list(client.list_backups(request=sample_request).pages) for page_, token in zip(pages, ["abc", "def", "ghi", ""]): assert page_.raw_page.next_page_token == token -def test_get_backup_collection_rest_use_cached_wrapped_rpc(): +def test_get_backup_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -8949,36 +9980,29 @@ def test_get_backup_collection_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert ( - client._transport.get_backup_collection - in client._transport._wrapped_methods - ) + assert client._transport.get_backup in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.Mock() mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.get_backup_collection] = ( - mock_rpc - ) + client._transport._wrapped_methods[client._transport.get_backup] = mock_rpc request = {} - client.get_backup_collection(request) + client.get_backup(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.get_backup_collection(request) + client.get_backup(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_get_backup_collection_rest_required_fields( - request_type=memorystore.GetBackupCollectionRequest, -): +def test_get_backup_rest_required_fields(request_type=memorystore.GetBackupRequest): transport_class = transports.MemorystoreRestTransport request_init = {} @@ -8993,7 +10017,7 @@ def test_get_backup_collection_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).get_backup_collection._get_unset_required_fields(jsonified_request) + ).get_backup._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present @@ -9002,7 +10026,7 @@ def test_get_backup_collection_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).get_backup_collection._get_unset_required_fields(jsonified_request) + ).get_backup._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone @@ -9016,7 +10040,7 @@ def test_get_backup_collection_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = memorystore.BackupCollection() + return_value = memorystore.Backup() # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values @@ -9037,30 +10061,30 @@ def test_get_backup_collection_rest_required_fields( response_value.status_code = 200 # Convert return value to protobuf type - return_value = memorystore.BackupCollection.pb(return_value) + return_value = memorystore.Backup.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.get_backup_collection(request) + response = client.get_backup(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert sorted(expected_params) == sorted(actual_params) -def test_get_backup_collection_rest_unset_required_fields(): +def test_get_backup_rest_unset_required_fields(): transport = transports.MemorystoreRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.get_backup_collection._get_unset_required_fields({}) + unset_fields = transport.get_backup._get_unset_required_fields({}) assert set(unset_fields) == (set(()) & set(("name",))) -def test_get_backup_collection_rest_flattened(): +def test_get_backup_rest_flattened(): client = MemorystoreClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -9069,11 +10093,11 @@ def test_get_backup_collection_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 = memorystore.BackupCollection() + return_value = memorystore.Backup() # get arguments that satisfy an http rule for this method sample_request = { - "name": "projects/sample1/locations/sample2/backupCollections/sample3" + "name": "projects/sample1/locations/sample2/backupCollections/sample3/backups/sample4" } # get truthy value for each flattened field @@ -9086,26 +10110,26 @@ def test_get_backup_collection_rest_flattened(): response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = memorystore.BackupCollection.pb(return_value) + return_value = memorystore.Backup.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.get_backup_collection(**mock_args) + client.get_backup(**mock_args) # Establish that the underlying call was made with the expected # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] assert path_template.validate( - "%s/v1/{name=projects/*/locations/*/backupCollections/*}" + "%s/v1/{name=projects/*/locations/*/backupCollections/*/backups/*}" % client.transport._host, args[1], ) -def test_get_backup_collection_rest_flattened_error(transport: str = "rest"): +def test_get_backup_rest_flattened_error(transport: str = "rest"): client = MemorystoreClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -9114,13 +10138,13 @@ def test_get_backup_collection_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_backup_collection( - memorystore.GetBackupCollectionRequest(), + client.get_backup( + memorystore.GetBackupRequest(), name="name_value", ) -def test_list_backups_rest_use_cached_wrapped_rpc(): +def test_delete_backup_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -9134,33 +10158,39 @@ def test_list_backups_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.list_backups in client._transport._wrapped_methods + assert client._transport.delete_backup in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.Mock() mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.list_backups] = mock_rpc + client._transport._wrapped_methods[client._transport.delete_backup] = mock_rpc request = {} - client.list_backups(request) + client.delete_backup(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.list_backups(request) + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.delete_backup(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_list_backups_rest_required_fields(request_type=memorystore.ListBackupsRequest): +def test_delete_backup_rest_required_fields( + request_type=memorystore.DeleteBackupRequest, +): transport_class = transports.MemorystoreRestTransport request_init = {} - request_init["parent"] = "" + request_init["name"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -9171,28 +10201,23 @@ def test_list_backups_rest_required_fields(request_type=memorystore.ListBackupsR unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).list_backups._get_unset_required_fields(jsonified_request) + ).delete_backup._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present - jsonified_request["parent"] = "parent_value" + jsonified_request["name"] = "name_value" unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).list_backups._get_unset_required_fields(jsonified_request) + ).delete_backup._get_unset_required_fields(jsonified_request) # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set( - ( - "page_size", - "page_token", - ) - ) + 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" + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" client = MemorystoreClient( credentials=ga_credentials.AnonymousCredentials(), @@ -9201,7 +10226,7 @@ def test_list_backups_rest_required_fields(request_type=memorystore.ListBackupsR request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = memorystore.ListBackupsResponse() + return_value = operations_pb2.Operation(name="operations/spam") # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values @@ -9213,47 +10238,36 @@ def test_list_backups_rest_required_fields(request_type=memorystore.ListBackupsR 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 = memorystore.ListBackupsResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.list_backups(request) + response = client.delete_backup(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert sorted(expected_params) == sorted(actual_params) -def test_list_backups_rest_unset_required_fields(): +def test_delete_backup_rest_unset_required_fields(): transport = transports.MemorystoreRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.list_backups._get_unset_required_fields({}) - assert set(unset_fields) == ( - set( - ( - "pageSize", - "pageToken", - ) - ) - & set(("parent",)) - ) + unset_fields = transport.delete_backup._get_unset_required_fields({}) + assert set(unset_fields) == (set(("requestId",)) & set(("name",))) -def test_list_backups_rest_flattened(): +def test_delete_backup_rest_flattened(): client = MemorystoreClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -9262,43 +10276,41 @@ def test_list_backups_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 = memorystore.ListBackupsResponse() + return_value = operations_pb2.Operation(name="operations/spam") # get arguments that satisfy an http rule for this method sample_request = { - "parent": "projects/sample1/locations/sample2/backupCollections/sample3" + "name": "projects/sample1/locations/sample2/backupCollections/sample3/backups/sample4" } # get truthy value for each flattened field mock_args = dict( - parent="parent_value", + name="name_value", ) mock_args.update(sample_request) # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 - # Convert return value to protobuf type - return_value = memorystore.ListBackupsResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.list_backups(**mock_args) + client.delete_backup(**mock_args) # Establish that the underlying call was made with the expected # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] assert path_template.validate( - "%s/v1/{parent=projects/*/locations/*/backupCollections/*}/backups" + "%s/v1/{name=projects/*/locations/*/backupCollections/*/backups/*}" % client.transport._host, args[1], ) -def test_list_backups_rest_flattened_error(transport: str = "rest"): +def test_delete_backup_rest_flattened_error(transport: str = "rest"): client = MemorystoreClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -9307,76 +10319,13 @@ def test_list_backups_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_backups( - memorystore.ListBackupsRequest(), - parent="parent_value", - ) - - -def test_list_backups_rest_pager(transport: str = "rest"): - client = MemorystoreClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, "request") as req: - # TODO(kbandes): remove this mock unless there's a good reason for it. - # with mock.patch.object(path_template, 'transcode') as transcode: - # Set the response as a series of pages - response = ( - memorystore.ListBackupsResponse( - backups=[ - memorystore.Backup(), - memorystore.Backup(), - memorystore.Backup(), - ], - next_page_token="abc", - ), - memorystore.ListBackupsResponse( - backups=[], - next_page_token="def", - ), - memorystore.ListBackupsResponse( - backups=[ - memorystore.Backup(), - ], - next_page_token="ghi", - ), - memorystore.ListBackupsResponse( - backups=[ - memorystore.Backup(), - memorystore.Backup(), - ], - ), + client.delete_backup( + memorystore.DeleteBackupRequest(), + name="name_value", ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(memorystore.ListBackupsResponse.to_json(x) for x in response) - return_values = tuple(Response() for i in response) - for return_val, response_val in zip(return_values, response): - return_val._content = response_val.encode("UTF-8") - return_val.status_code = 200 - req.side_effect = return_values - - sample_request = { - "parent": "projects/sample1/locations/sample2/backupCollections/sample3" - } - - pager = client.list_backups(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, memorystore.Backup) for i in results) - - pages = list(client.list_backups(request=sample_request).pages) - for page_, token in zip(pages, ["abc", "def", "ghi", ""]): - assert page_.raw_page.next_page_token == token -def test_get_backup_rest_use_cached_wrapped_rpc(): +def test_export_backup_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -9390,29 +10339,35 @@ def test_get_backup_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.get_backup in client._transport._wrapped_methods + assert client._transport.export_backup in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.Mock() mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.get_backup] = mock_rpc + client._transport._wrapped_methods[client._transport.export_backup] = mock_rpc request = {} - client.get_backup(request) + client.export_backup(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.get_backup(request) + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.export_backup(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_get_backup_rest_required_fields(request_type=memorystore.GetBackupRequest): +def test_export_backup_rest_required_fields( + request_type=memorystore.ExportBackupRequest, +): transport_class = transports.MemorystoreRestTransport request_init = {} @@ -9427,7 +10382,7 @@ def test_get_backup_rest_required_fields(request_type=memorystore.GetBackupReque unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).get_backup._get_unset_required_fields(jsonified_request) + ).export_backup._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present @@ -9436,7 +10391,7 @@ def test_get_backup_rest_required_fields(request_type=memorystore.GetBackupReque unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).get_backup._get_unset_required_fields(jsonified_request) + ).export_backup._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone @@ -9450,7 +10405,7 @@ def test_get_backup_rest_required_fields(request_type=memorystore.GetBackupReque request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = memorystore.Backup() + return_value = operations_pb2.Operation(name="operations/spam") # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values @@ -9462,99 +10417,37 @@ def test_get_backup_rest_required_fields(request_type=memorystore.GetBackupReque 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 = memorystore.Backup.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.get_backup(request) + response = client.export_backup(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert sorted(expected_params) == sorted(actual_params) -def test_get_backup_rest_unset_required_fields(): +def test_export_backup_rest_unset_required_fields(): transport = transports.MemorystoreRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.get_backup._get_unset_required_fields({}) + unset_fields = transport.export_backup._get_unset_required_fields({}) assert set(unset_fields) == (set(()) & set(("name",))) -def test_get_backup_rest_flattened(): - client = MemorystoreClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), "request") as req: - # Designate an appropriate value for the returned response. - return_value = memorystore.Backup() - - # get arguments that satisfy an http rule for this method - sample_request = { - "name": "projects/sample1/locations/sample2/backupCollections/sample3/backups/sample4" - } - - # get truthy value for each flattened field - mock_args = dict( - name="name_value", - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = memorystore.Backup.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - client.get_backup(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate( - "%s/v1/{name=projects/*/locations/*/backupCollections/*/backups/*}" - % client.transport._host, - args[1], - ) - - -def test_get_backup_rest_flattened_error(transport: str = "rest"): - client = MemorystoreClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.get_backup( - memorystore.GetBackupRequest(), - name="name_value", - ) - - -def test_delete_backup_rest_use_cached_wrapped_rpc(): +def test_backup_instance_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -9568,17 +10461,17 @@ def test_delete_backup_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.delete_backup in client._transport._wrapped_methods + assert client._transport.backup_instance in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.Mock() mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.delete_backup] = mock_rpc + client._transport._wrapped_methods[client._transport.backup_instance] = mock_rpc request = {} - client.delete_backup(request) + client.backup_instance(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 @@ -9587,15 +10480,15 @@ def test_delete_backup_rest_use_cached_wrapped_rpc(): # subsequent calls should use the cached wrapper wrapper_fn.reset_mock() - client.delete_backup(request) + client.backup_instance(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_delete_backup_rest_required_fields( - request_type=memorystore.DeleteBackupRequest, +def test_backup_instance_rest_required_fields( + request_type=memorystore.BackupInstanceRequest, ): transport_class = transports.MemorystoreRestTransport @@ -9611,7 +10504,7 @@ def test_delete_backup_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).delete_backup._get_unset_required_fields(jsonified_request) + ).backup_instance._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present @@ -9620,9 +10513,7 @@ def test_delete_backup_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).delete_backup._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("request_id",)) + ).backup_instance._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone @@ -9648,9 +10539,10 @@ def test_delete_backup_rest_required_fields( pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "delete", + "method": "post", "query_params": pb_request, } + transcode_result["body"] = pb_request transcode.return_value = transcode_result response_value = Response() @@ -9661,23 +10553,23 @@ def test_delete_backup_rest_required_fields( req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.delete_backup(request) + response = client.backup_instance(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert sorted(expected_params) == sorted(actual_params) -def test_delete_backup_rest_unset_required_fields(): +def test_backup_instance_rest_unset_required_fields(): transport = transports.MemorystoreRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.delete_backup._get_unset_required_fields({}) - assert set(unset_fields) == (set(("requestId",)) & set(("name",))) + unset_fields = transport.backup_instance._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) -def test_delete_backup_rest_flattened(): +def test_backup_instance_rest_flattened(): client = MemorystoreClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -9690,7 +10582,7 @@ def test_delete_backup_rest_flattened(): # get arguments that satisfy an http rule for this method sample_request = { - "name": "projects/sample1/locations/sample2/backupCollections/sample3/backups/sample4" + "name": "projects/sample1/locations/sample2/instances/sample3" } # get truthy value for each flattened field @@ -9707,20 +10599,20 @@ def test_delete_backup_rest_flattened(): req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.delete_backup(**mock_args) + client.backup_instance(**mock_args) # Establish that the underlying call was made with the expected # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] assert path_template.validate( - "%s/v1/{name=projects/*/locations/*/backupCollections/*/backups/*}" + "%s/v1/{name=projects/*/locations/*/instances/*}:backup" % client.transport._host, args[1], ) -def test_delete_backup_rest_flattened_error(transport: str = "rest"): +def test_backup_instance_rest_flattened_error(transport: str = "rest"): client = MemorystoreClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -9729,13 +10621,13 @@ def test_delete_backup_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_backup( - memorystore.DeleteBackupRequest(), + client.backup_instance( + memorystore.BackupInstanceRequest(), name="name_value", ) -def test_export_backup_rest_use_cached_wrapped_rpc(): +def test_start_migration_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -9749,17 +10641,17 @@ def test_export_backup_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.export_backup in client._transport._wrapped_methods + assert client._transport.start_migration in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.Mock() mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.export_backup] = mock_rpc + client._transport._wrapped_methods[client._transport.start_migration] = mock_rpc request = {} - client.export_backup(request) + client.start_migration(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 @@ -9768,15 +10660,15 @@ def test_export_backup_rest_use_cached_wrapped_rpc(): # subsequent calls should use the cached wrapper wrapper_fn.reset_mock() - client.export_backup(request) + client.start_migration(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_export_backup_rest_required_fields( - request_type=memorystore.ExportBackupRequest, +def test_start_migration_rest_required_fields( + request_type=memorystore.StartMigrationRequest, ): transport_class = transports.MemorystoreRestTransport @@ -9792,7 +10684,7 @@ def test_export_backup_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).export_backup._get_unset_required_fields(jsonified_request) + ).start_migration._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present @@ -9801,7 +10693,7 @@ def test_export_backup_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).export_backup._get_unset_required_fields(jsonified_request) + ).start_migration._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone @@ -9841,23 +10733,31 @@ def test_export_backup_rest_required_fields( req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.export_backup(request) + response = client.start_migration(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert sorted(expected_params) == sorted(actual_params) -def test_export_backup_rest_unset_required_fields(): +def test_start_migration_rest_unset_required_fields(): transport = transports.MemorystoreRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.export_backup._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name",))) + unset_fields = transport.start_migration._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(()) + & set( + ( + "selfManagedSource", + "name", + ) + ) + ) -def test_backup_instance_rest_use_cached_wrapped_rpc(): +def test_finish_migration_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -9871,17 +10771,19 @@ def test_backup_instance_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.backup_instance in client._transport._wrapped_methods + assert client._transport.finish_migration in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.Mock() mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.backup_instance] = mock_rpc + client._transport._wrapped_methods[client._transport.finish_migration] = ( + mock_rpc + ) request = {} - client.backup_instance(request) + client.finish_migration(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 @@ -9890,15 +10792,15 @@ def test_backup_instance_rest_use_cached_wrapped_rpc(): # subsequent calls should use the cached wrapper wrapper_fn.reset_mock() - client.backup_instance(request) + client.finish_migration(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_backup_instance_rest_required_fields( - request_type=memorystore.BackupInstanceRequest, +def test_finish_migration_rest_required_fields( + request_type=memorystore.FinishMigrationRequest, ): transport_class = transports.MemorystoreRestTransport @@ -9914,7 +10816,7 @@ def test_backup_instance_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).backup_instance._get_unset_required_fields(jsonified_request) + ).finish_migration._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present @@ -9923,7 +10825,7 @@ def test_backup_instance_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).backup_instance._get_unset_required_fields(jsonified_request) + ).finish_migration._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone @@ -9963,23 +10865,23 @@ def test_backup_instance_rest_required_fields( req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.backup_instance(request) + response = client.finish_migration(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert sorted(expected_params) == sorted(actual_params) -def test_backup_instance_rest_unset_required_fields(): +def test_finish_migration_rest_unset_required_fields(): transport = transports.MemorystoreRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.backup_instance._get_unset_required_fields({}) + unset_fields = transport.finish_migration._get_unset_required_fields({}) assert set(unset_fields) == (set(()) & set(("name",))) -def test_backup_instance_rest_flattened(): +def test_finish_migration_rest_flattened(): client = MemorystoreClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -9998,6 +10900,7 @@ def test_backup_instance_rest_flattened(): # get truthy value for each flattened field mock_args = dict( name="name_value", + force=True, ) mock_args.update(sample_request) @@ -10009,20 +10912,20 @@ def test_backup_instance_rest_flattened(): req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.backup_instance(**mock_args) + client.finish_migration(**mock_args) # Establish that the underlying call was made with the expected # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] assert path_template.validate( - "%s/v1/{name=projects/*/locations/*/instances/*}:backup" + "%s/v1/{name=projects/*/locations/*/instances/*}:finishMigration" % client.transport._host, args[1], ) -def test_backup_instance_rest_flattened_error(transport: str = "rest"): +def test_finish_migration_rest_flattened_error(transport: str = "rest"): client = MemorystoreClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -10031,9 +10934,10 @@ def test_backup_instance_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.backup_instance( - memorystore.BackupInstanceRequest(), + client.finish_migration( + memorystore.FinishMigrationRequest(), name="name_value", + force=True, ) @@ -10453,6 +11357,46 @@ def test_backup_instance_empty_call_grpc(): assert args[0] == request_msg +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_start_migration_empty_call_grpc(): + client = MemorystoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.start_migration), "__call__") as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.start_migration(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = memorystore.StartMigrationRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_finish_migration_empty_call_grpc(): + client = MemorystoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.finish_migration), "__call__") as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.finish_migration(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = memorystore.FinishMigrationRequest() + assert args[0] == request_msg + + def test_transport_kind_grpc_asyncio(): transport = MemorystoreAsyncClient.get_transport_class("grpc_asyncio")( credentials=async_anonymous_credentials() @@ -10896,6 +11840,54 @@ async def test_backup_instance_empty_call_grpc_asyncio(): assert args[0] == request_msg +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_start_migration_empty_call_grpc_asyncio(): + client = MemorystoreAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.start_migration), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + await client.start_migration(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = memorystore.StartMigrationRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_finish_migration_empty_call_grpc_asyncio(): + client = MemorystoreAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.finish_migration), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + await client.finish_migration(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = memorystore.FinishMigrationRequest() + assert args[0] == request_msg + + def test_transport_kind_rest(): transport = MemorystoreClient.get_transport_class("rest")( credentials=ga_credentials.AnonymousCredentials() @@ -11385,6 +12377,15 @@ def test_create_instance_rest_call_success(request_type): "server_ca_mode": 1, "server_ca_pool": "server_ca_pool_value", "rotate_server_certificate": True, + "migration_config": { + "self_managed_source": { + "ip_address": "ip_address_value", + "port": 453, + "network_attachment": "network_attachment_value", + }, + "state": 1, + "force_finish_migration": True, + }, } # The version of a generated dependency at test runtime may differ from the version used during generation. # Delete any fields which are not present in the current runtime dependency @@ -11705,6 +12706,15 @@ def test_update_instance_rest_call_success(request_type): "server_ca_mode": 1, "server_ca_pool": "server_ca_pool_value", "rotate_server_certificate": True, + "migration_config": { + "self_managed_source": { + "ip_address": "ip_address_value", + "port": 453, + "network_attachment": "network_attachment_value", + }, + "state": 1, + "force_finish_migration": True, + }, } # The version of a generated dependency at test runtime may differ from the version used during generation. # Delete any fields which are not present in the current runtime dependency @@ -11761,18 +12771,143 @@ def get_message_fields(field): } ) - # Remove fields from the sample request which are not present in the runtime version of the dependency - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER - field = subfield_to_delete.get("field") - field_repeated = subfield_to_delete.get("is_repeated") - subfield = subfield_to_delete.get("subfield") - if subfield: - if field_repeated: - for i in range(0, len(request_init["instance"][field])): - del request_init["instance"][field][i][subfield] - else: - del request_init["instance"][field][subfield] + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["instance"][field])): + del request_init["instance"][field][i][subfield] + else: + del request_init["instance"][field][subfield] + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.update_instance(request) + + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_instance_rest_interceptors(null_interceptor): + transport = transports.MemorystoreRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.MemorystoreRestInterceptor(), + ) + client = MemorystoreClient(transport=transport) + + with ( + mock.patch.object(type(client.transport._session), "request") as req, + mock.patch.object(path_template, "transcode") as transcode, + mock.patch.object(operation.Operation, "_set_result_from_operation"), + mock.patch.object( + transports.MemorystoreRestInterceptor, "post_update_instance" + ) as post, + mock.patch.object( + transports.MemorystoreRestInterceptor, "post_update_instance_with_metadata" + ) as post_with_metadata, + mock.patch.object( + transports.MemorystoreRestInterceptor, "pre_update_instance" + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = memorystore.UpdateInstanceRequest.pb( + memorystore.UpdateInstanceRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = memorystore.UpdateInstanceRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + post_with_metadata.return_value = operations_pb2.Operation(), metadata + + client.update_instance( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_delete_instance_rest_bad_request( + request_type=memorystore.DeleteInstanceRequest, +): + client = MemorystoreClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/instances/sample3"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.delete_instance(request) + + +@pytest.mark.parametrize( + "request_type", + [ + memorystore.DeleteInstanceRequest, + dict, + ], +) +def test_delete_instance_rest_call_success(request_type): + client = MemorystoreClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/instances/sample3"} request = request_type(**request_init) # Mock the http request call within the method and fake a response. @@ -11787,14 +12922,14 @@ def get_message_fields(field): response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.update_instance(request) + response = client.delete_instance(request) # Establish that the response is the type that we expect. json_return_value = json_format.MessageToJson(return_value) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_update_instance_rest_interceptors(null_interceptor): +def test_delete_instance_rest_interceptors(null_interceptor): transport = transports.MemorystoreRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -11808,20 +12943,20 @@ def test_update_instance_rest_interceptors(null_interceptor): mock.patch.object(path_template, "transcode") as transcode, mock.patch.object(operation.Operation, "_set_result_from_operation"), mock.patch.object( - transports.MemorystoreRestInterceptor, "post_update_instance" + transports.MemorystoreRestInterceptor, "post_delete_instance" ) as post, mock.patch.object( - transports.MemorystoreRestInterceptor, "post_update_instance_with_metadata" + transports.MemorystoreRestInterceptor, "post_delete_instance_with_metadata" ) as post_with_metadata, mock.patch.object( - transports.MemorystoreRestInterceptor, "pre_update_instance" + transports.MemorystoreRestInterceptor, "pre_delete_instance" ) as pre, ): pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = memorystore.UpdateInstanceRequest.pb( - memorystore.UpdateInstanceRequest() + pb_message = memorystore.DeleteInstanceRequest.pb( + memorystore.DeleteInstanceRequest() ) transcode.return_value = { "method": "post", @@ -11836,7 +12971,7 @@ def test_update_instance_rest_interceptors(null_interceptor): return_value = json_format.MessageToJson(operations_pb2.Operation()) req.return_value.content = return_value - request = memorystore.UpdateInstanceRequest() + request = memorystore.DeleteInstanceRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), @@ -11845,7 +12980,7 @@ def test_update_instance_rest_interceptors(null_interceptor): post.return_value = operations_pb2.Operation() post_with_metadata.return_value = operations_pb2.Operation(), metadata - client.update_instance( + client.delete_instance( request, metadata=[ ("key", "val"), @@ -11858,8 +12993,8 @@ def test_update_instance_rest_interceptors(null_interceptor): post_with_metadata.assert_called_once() -def test_delete_instance_rest_bad_request( - request_type=memorystore.DeleteInstanceRequest, +def test_get_certificate_authority_rest_bad_request( + request_type=memorystore.GetCertificateAuthorityRequest, ): client = MemorystoreClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" @@ -11881,17 +13016,17 @@ def test_delete_instance_rest_bad_request( response_value.request = mock.Mock() req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.delete_instance(request) + client.get_certificate_authority(request) @pytest.mark.parametrize( "request_type", [ - memorystore.DeleteInstanceRequest, + memorystore.GetCertificateAuthorityRequest, dict, ], ) -def test_delete_instance_rest_call_success(request_type): +def test_get_certificate_authority_rest_call_success(request_type): client = MemorystoreClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) @@ -11903,23 +13038,29 @@ def test_delete_instance_rest_call_success(request_type): # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name="operations/spam") + return_value = memorystore.CertificateAuthority( + name="name_value", + ) # Wrap the value into a proper Response obj response_value = mock.Mock() response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = memorystore.CertificateAuthority.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.delete_instance(request) + response = client.get_certificate_authority(request) # Establish that the response is the type that we expect. - json_return_value = json_format.MessageToJson(return_value) + assert isinstance(response, memorystore.CertificateAuthority) + assert response.name == "name_value" @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_delete_instance_rest_interceptors(null_interceptor): +def test_get_certificate_authority_rest_interceptors(null_interceptor): transport = transports.MemorystoreRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -11931,22 +13072,22 @@ def test_delete_instance_rest_interceptors(null_interceptor): with ( mock.patch.object(type(client.transport._session), "request") as req, mock.patch.object(path_template, "transcode") as transcode, - mock.patch.object(operation.Operation, "_set_result_from_operation"), mock.patch.object( - transports.MemorystoreRestInterceptor, "post_delete_instance" + transports.MemorystoreRestInterceptor, "post_get_certificate_authority" ) as post, mock.patch.object( - transports.MemorystoreRestInterceptor, "post_delete_instance_with_metadata" + transports.MemorystoreRestInterceptor, + "post_get_certificate_authority_with_metadata", ) as post_with_metadata, mock.patch.object( - transports.MemorystoreRestInterceptor, "pre_delete_instance" + transports.MemorystoreRestInterceptor, "pre_get_certificate_authority" ) as pre, ): pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = memorystore.DeleteInstanceRequest.pb( - memorystore.DeleteInstanceRequest() + pb_message = memorystore.GetCertificateAuthorityRequest.pb( + memorystore.GetCertificateAuthorityRequest() ) transcode.return_value = { "method": "post", @@ -11958,19 +13099,21 @@ def test_delete_instance_rest_interceptors(null_interceptor): req.return_value = mock.Mock() req.return_value.status_code = 200 req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - return_value = json_format.MessageToJson(operations_pb2.Operation()) + return_value = memorystore.CertificateAuthority.to_json( + memorystore.CertificateAuthority() + ) req.return_value.content = return_value - request = memorystore.DeleteInstanceRequest() + request = memorystore.GetCertificateAuthorityRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - post_with_metadata.return_value = operations_pb2.Operation(), metadata + post.return_value = memorystore.CertificateAuthority() + post_with_metadata.return_value = memorystore.CertificateAuthority(), metadata - client.delete_instance( + client.get_certificate_authority( request, metadata=[ ("key", "val"), @@ -11983,14 +13126,16 @@ def test_delete_instance_rest_interceptors(null_interceptor): post_with_metadata.assert_called_once() -def test_get_certificate_authority_rest_bad_request( - request_type=memorystore.GetCertificateAuthorityRequest, +def test_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/instances/sample3"} + 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. @@ -12006,29 +13151,31 @@ def test_get_certificate_authority_rest_bad_request( response_value.request = mock.Mock() req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.get_certificate_authority(request) + client.get_shared_regional_certificate_authority(request) @pytest.mark.parametrize( "request_type", [ - memorystore.GetCertificateAuthorityRequest, + memorystore.GetSharedRegionalCertificateAuthorityRequest, dict, ], ) -def test_get_certificate_authority_rest_call_success(request_type): +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/instances/sample3"} + 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.CertificateAuthority( + return_value = memorystore.SharedRegionalCertificateAuthority( name="name_value", ) @@ -12037,20 +13184,20 @@ def test_get_certificate_authority_rest_call_success(request_type): response_value.status_code = 200 # Convert return value to protobuf type - return_value = memorystore.CertificateAuthority.pb(return_value) + 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_certificate_authority(request) + response = client.get_shared_regional_certificate_authority(request) # Establish that the response is the type that we expect. - assert isinstance(response, memorystore.CertificateAuthority) + assert isinstance(response, memorystore.SharedRegionalCertificateAuthority) assert response.name == "name_value" @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_certificate_authority_rest_interceptors(null_interceptor): +def test_get_shared_regional_certificate_authority_rest_interceptors(null_interceptor): transport = transports.MemorystoreRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -12063,21 +13210,23 @@ def test_get_certificate_authority_rest_interceptors(null_interceptor): mock.patch.object(type(client.transport._session), "request") as req, mock.patch.object(path_template, "transcode") as transcode, mock.patch.object( - transports.MemorystoreRestInterceptor, "post_get_certificate_authority" + transports.MemorystoreRestInterceptor, + "post_get_shared_regional_certificate_authority", ) as post, mock.patch.object( transports.MemorystoreRestInterceptor, - "post_get_certificate_authority_with_metadata", + "post_get_shared_regional_certificate_authority_with_metadata", ) as post_with_metadata, mock.patch.object( - transports.MemorystoreRestInterceptor, "pre_get_certificate_authority" + 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.GetCertificateAuthorityRequest.pb( - memorystore.GetCertificateAuthorityRequest() + pb_message = memorystore.GetSharedRegionalCertificateAuthorityRequest.pb( + memorystore.GetSharedRegionalCertificateAuthorityRequest() ) transcode.return_value = { "method": "post", @@ -12089,21 +13238,150 @@ def test_get_certificate_authority_rest_interceptors(null_interceptor): req.return_value = mock.Mock() req.return_value.status_code = 200 req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - return_value = memorystore.CertificateAuthority.to_json( - memorystore.CertificateAuthority() + return_value = memorystore.SharedRegionalCertificateAuthority.to_json( + memorystore.SharedRegionalCertificateAuthority() + ) + req.return_value.content = return_value + + request = memorystore.GetSharedRegionalCertificateAuthorityRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = memorystore.SharedRegionalCertificateAuthority() + post_with_metadata.return_value = ( + memorystore.SharedRegionalCertificateAuthority(), + metadata, + ) + + client.get_shared_regional_certificate_authority( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_reschedule_maintenance_rest_bad_request( + request_type=memorystore.RescheduleMaintenanceRequest, +): + client = MemorystoreClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/instances/sample3"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.reschedule_maintenance(request) + + +@pytest.mark.parametrize( + "request_type", + [ + memorystore.RescheduleMaintenanceRequest, + dict, + ], +) +def test_reschedule_maintenance_rest_call_success(request_type): + client = MemorystoreClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/instances/sample3"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.reschedule_maintenance(request) + + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_reschedule_maintenance_rest_interceptors(null_interceptor): + transport = transports.MemorystoreRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.MemorystoreRestInterceptor(), + ) + client = MemorystoreClient(transport=transport) + + with ( + mock.patch.object(type(client.transport._session), "request") as req, + mock.patch.object(path_template, "transcode") as transcode, + mock.patch.object(operation.Operation, "_set_result_from_operation"), + mock.patch.object( + transports.MemorystoreRestInterceptor, "post_reschedule_maintenance" + ) as post, + mock.patch.object( + transports.MemorystoreRestInterceptor, + "post_reschedule_maintenance_with_metadata", + ) as post_with_metadata, + mock.patch.object( + transports.MemorystoreRestInterceptor, "pre_reschedule_maintenance" + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = memorystore.RescheduleMaintenanceRequest.pb( + memorystore.RescheduleMaintenanceRequest() ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = json_format.MessageToJson(operations_pb2.Operation()) req.return_value.content = return_value - request = memorystore.GetCertificateAuthorityRequest() + request = memorystore.RescheduleMaintenanceRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = memorystore.CertificateAuthority() - post_with_metadata.return_value = memorystore.CertificateAuthority(), metadata + post.return_value = operations_pb2.Operation() + post_with_metadata.return_value = operations_pb2.Operation(), metadata - client.get_certificate_authority( + client.reschedule_maintenance( request, metadata=[ ("key", "val"), @@ -12116,16 +13394,14 @@ def test_get_certificate_authority_rest_interceptors(null_interceptor): post_with_metadata.assert_called_once() -def test_get_shared_regional_certificate_authority_rest_bad_request( - request_type=memorystore.GetSharedRegionalCertificateAuthorityRequest, +def test_list_backup_collections_rest_bad_request( + request_type=memorystore.ListBackupCollectionsRequest, ): client = MemorystoreClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = { - "name": "projects/sample1/locations/sample2/sharedRegionalCertificateAuthority" - } + request_init = {"parent": "projects/sample1/locations/sample2"} request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -12141,32 +13417,31 @@ def test_get_shared_regional_certificate_authority_rest_bad_request( response_value.request = mock.Mock() req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.get_shared_regional_certificate_authority(request) + client.list_backup_collections(request) @pytest.mark.parametrize( "request_type", [ - memorystore.GetSharedRegionalCertificateAuthorityRequest, + memorystore.ListBackupCollectionsRequest, dict, ], ) -def test_get_shared_regional_certificate_authority_rest_call_success(request_type): +def test_list_backup_collections_rest_call_success(request_type): client = MemorystoreClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = { - "name": "projects/sample1/locations/sample2/sharedRegionalCertificateAuthority" - } + request_init = {"parent": "projects/sample1/locations/sample2"} request = request_type(**request_init) # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = memorystore.SharedRegionalCertificateAuthority( - name="name_value", + return_value = memorystore.ListBackupCollectionsResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], ) # Wrap the value into a proper Response obj @@ -12174,20 +13449,21 @@ def test_get_shared_regional_certificate_authority_rest_call_success(request_typ response_value.status_code = 200 # Convert return value to protobuf type - return_value = memorystore.SharedRegionalCertificateAuthority.pb(return_value) + return_value = memorystore.ListBackupCollectionsResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.get_shared_regional_certificate_authority(request) + response = client.list_backup_collections(request) # Establish that the response is the type that we expect. - assert isinstance(response, memorystore.SharedRegionalCertificateAuthority) - assert response.name == "name_value" + assert isinstance(response, pagers.ListBackupCollectionsPager) + assert response.next_page_token == "next_page_token_value" + assert response.unreachable == ["unreachable_value"] @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_shared_regional_certificate_authority_rest_interceptors(null_interceptor): +def test_list_backup_collections_rest_interceptors(null_interceptor): transport = transports.MemorystoreRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -12200,23 +13476,21 @@ def test_get_shared_regional_certificate_authority_rest_interceptors(null_interc 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", + transports.MemorystoreRestInterceptor, "post_list_backup_collections" ) as post, mock.patch.object( transports.MemorystoreRestInterceptor, - "post_get_shared_regional_certificate_authority_with_metadata", + "post_list_backup_collections_with_metadata", ) as post_with_metadata, mock.patch.object( - transports.MemorystoreRestInterceptor, - "pre_get_shared_regional_certificate_authority", + transports.MemorystoreRestInterceptor, "pre_list_backup_collections" ) as pre, ): pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = memorystore.GetSharedRegionalCertificateAuthorityRequest.pb( - memorystore.GetSharedRegionalCertificateAuthorityRequest() + pb_message = memorystore.ListBackupCollectionsRequest.pb( + memorystore.ListBackupCollectionsRequest() ) transcode.return_value = { "method": "post", @@ -12228,24 +13502,24 @@ def test_get_shared_regional_certificate_authority_rest_interceptors(null_interc req.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() + return_value = memorystore.ListBackupCollectionsResponse.to_json( + memorystore.ListBackupCollectionsResponse() ) req.return_value.content = return_value - request = memorystore.GetSharedRegionalCertificateAuthorityRequest() + request = memorystore.ListBackupCollectionsRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = memorystore.SharedRegionalCertificateAuthority() + post.return_value = memorystore.ListBackupCollectionsResponse() post_with_metadata.return_value = ( - memorystore.SharedRegionalCertificateAuthority(), + memorystore.ListBackupCollectionsResponse(), metadata, ) - client.get_shared_regional_certificate_authority( + client.list_backup_collections( request, metadata=[ ("key", "val"), @@ -12258,14 +13532,16 @@ def test_get_shared_regional_certificate_authority_rest_interceptors(null_interc post_with_metadata.assert_called_once() -def test_reschedule_maintenance_rest_bad_request( - request_type=memorystore.RescheduleMaintenanceRequest, +def test_get_backup_collection_rest_bad_request( + request_type=memorystore.GetBackupCollectionRequest, ): client = MemorystoreClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/locations/sample2/instances/sample3"} + request_init = { + "name": "projects/sample1/locations/sample2/backupCollections/sample3" + } request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -12281,45 +13557,65 @@ def test_reschedule_maintenance_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.reschedule_maintenance(request) + client.get_backup_collection(request) @pytest.mark.parametrize( "request_type", [ - memorystore.RescheduleMaintenanceRequest, + memorystore.GetBackupCollectionRequest, dict, ], ) -def test_reschedule_maintenance_rest_call_success(request_type): +def test_get_backup_collection_rest_call_success(request_type): client = MemorystoreClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/locations/sample2/instances/sample3"} + request_init = { + "name": "projects/sample1/locations/sample2/backupCollections/sample3" + } request = request_type(**request_init) # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name="operations/spam") + return_value = memorystore.BackupCollection( + name="name_value", + instance_uid="instance_uid_value", + instance="instance_value", + kms_key="kms_key_value", + uid="uid_value", + total_backup_size_bytes=2457, + total_backup_count=1921, + ) # Wrap the value into a proper Response obj response_value = mock.Mock() response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = memorystore.BackupCollection.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.reschedule_maintenance(request) + response = client.get_backup_collection(request) # Establish that the response is the type that we expect. - json_return_value = json_format.MessageToJson(return_value) + assert isinstance(response, memorystore.BackupCollection) + assert response.name == "name_value" + assert response.instance_uid == "instance_uid_value" + assert response.instance == "instance_value" + assert response.kms_key == "kms_key_value" + assert response.uid == "uid_value" + assert response.total_backup_size_bytes == 2457 + assert response.total_backup_count == 1921 @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_reschedule_maintenance_rest_interceptors(null_interceptor): +def test_get_backup_collection_rest_interceptors(null_interceptor): transport = transports.MemorystoreRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -12331,23 +13627,22 @@ def test_reschedule_maintenance_rest_interceptors(null_interceptor): with ( mock.patch.object(type(client.transport._session), "request") as req, mock.patch.object(path_template, "transcode") as transcode, - mock.patch.object(operation.Operation, "_set_result_from_operation"), mock.patch.object( - transports.MemorystoreRestInterceptor, "post_reschedule_maintenance" + transports.MemorystoreRestInterceptor, "post_get_backup_collection" ) as post, mock.patch.object( transports.MemorystoreRestInterceptor, - "post_reschedule_maintenance_with_metadata", + "post_get_backup_collection_with_metadata", ) as post_with_metadata, mock.patch.object( - transports.MemorystoreRestInterceptor, "pre_reschedule_maintenance" + transports.MemorystoreRestInterceptor, "pre_get_backup_collection" ) as pre, ): pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = memorystore.RescheduleMaintenanceRequest.pb( - memorystore.RescheduleMaintenanceRequest() + pb_message = memorystore.GetBackupCollectionRequest.pb( + memorystore.GetBackupCollectionRequest() ) transcode.return_value = { "method": "post", @@ -12359,19 +13654,21 @@ def test_reschedule_maintenance_rest_interceptors(null_interceptor): req.return_value = mock.Mock() req.return_value.status_code = 200 req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - return_value = json_format.MessageToJson(operations_pb2.Operation()) + return_value = memorystore.BackupCollection.to_json( + memorystore.BackupCollection() + ) req.return_value.content = return_value - request = memorystore.RescheduleMaintenanceRequest() + request = memorystore.GetBackupCollectionRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - post_with_metadata.return_value = operations_pb2.Operation(), metadata + post.return_value = memorystore.BackupCollection() + post_with_metadata.return_value = memorystore.BackupCollection(), metadata - client.reschedule_maintenance( + client.get_backup_collection( request, metadata=[ ("key", "val"), @@ -12384,14 +13681,14 @@ def test_reschedule_maintenance_rest_interceptors(null_interceptor): post_with_metadata.assert_called_once() -def test_list_backup_collections_rest_bad_request( - request_type=memorystore.ListBackupCollectionsRequest, -): +def test_list_backups_rest_bad_request(request_type=memorystore.ListBackupsRequest): client = MemorystoreClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/locations/sample2"} + request_init = { + "parent": "projects/sample1/locations/sample2/backupCollections/sample3" + } request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -12407,29 +13704,31 @@ def test_list_backup_collections_rest_bad_request( response_value.request = mock.Mock() req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.list_backup_collections(request) + client.list_backups(request) @pytest.mark.parametrize( "request_type", [ - memorystore.ListBackupCollectionsRequest, + memorystore.ListBackupsRequest, dict, ], ) -def test_list_backup_collections_rest_call_success(request_type): +def test_list_backups_rest_call_success(request_type): client = MemorystoreClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/locations/sample2"} + request_init = { + "parent": "projects/sample1/locations/sample2/backupCollections/sample3" + } request = request_type(**request_init) # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = memorystore.ListBackupCollectionsResponse( + return_value = memorystore.ListBackupsResponse( next_page_token="next_page_token_value", unreachable=["unreachable_value"], ) @@ -12439,21 +13738,21 @@ def test_list_backup_collections_rest_call_success(request_type): response_value.status_code = 200 # Convert return value to protobuf type - return_value = memorystore.ListBackupCollectionsResponse.pb(return_value) + return_value = memorystore.ListBackupsResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.list_backup_collections(request) + response = client.list_backups(request) # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListBackupCollectionsPager) + assert isinstance(response, pagers.ListBackupsPager) assert response.next_page_token == "next_page_token_value" assert response.unreachable == ["unreachable_value"] @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_backup_collections_rest_interceptors(null_interceptor): +def test_list_backups_rest_interceptors(null_interceptor): transport = transports.MemorystoreRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -12466,22 +13765,19 @@ def test_list_backup_collections_rest_interceptors(null_interceptor): mock.patch.object(type(client.transport._session), "request") as req, mock.patch.object(path_template, "transcode") as transcode, mock.patch.object( - transports.MemorystoreRestInterceptor, "post_list_backup_collections" + transports.MemorystoreRestInterceptor, "post_list_backups" ) as post, mock.patch.object( - transports.MemorystoreRestInterceptor, - "post_list_backup_collections_with_metadata", + transports.MemorystoreRestInterceptor, "post_list_backups_with_metadata" ) as post_with_metadata, mock.patch.object( - transports.MemorystoreRestInterceptor, "pre_list_backup_collections" + transports.MemorystoreRestInterceptor, "pre_list_backups" ) as pre, ): pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = memorystore.ListBackupCollectionsRequest.pb( - memorystore.ListBackupCollectionsRequest() - ) + pb_message = memorystore.ListBackupsRequest.pb(memorystore.ListBackupsRequest()) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -12492,24 +13788,21 @@ def test_list_backup_collections_rest_interceptors(null_interceptor): req.return_value = mock.Mock() req.return_value.status_code = 200 req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - return_value = memorystore.ListBackupCollectionsResponse.to_json( - memorystore.ListBackupCollectionsResponse() + return_value = memorystore.ListBackupsResponse.to_json( + memorystore.ListBackupsResponse() ) req.return_value.content = return_value - request = memorystore.ListBackupCollectionsRequest() + request = memorystore.ListBackupsRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = memorystore.ListBackupCollectionsResponse() - post_with_metadata.return_value = ( - memorystore.ListBackupCollectionsResponse(), - metadata, - ) + post.return_value = memorystore.ListBackupsResponse() + post_with_metadata.return_value = memorystore.ListBackupsResponse(), metadata - client.list_backup_collections( + client.list_backups( request, metadata=[ ("key", "val"), @@ -12522,15 +13815,13 @@ def test_list_backup_collections_rest_interceptors(null_interceptor): post_with_metadata.assert_called_once() -def test_get_backup_collection_rest_bad_request( - request_type=memorystore.GetBackupCollectionRequest, -): +def test_get_backup_rest_bad_request(request_type=memorystore.GetBackupRequest): client = MemorystoreClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding request_init = { - "name": "projects/sample1/locations/sample2/backupCollections/sample3" + "name": "projects/sample1/locations/sample2/backupCollections/sample3/backups/sample4" } request = request_type(**request_init) @@ -12547,38 +13838,42 @@ def test_get_backup_collection_rest_bad_request( response_value.request = mock.Mock() req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.get_backup_collection(request) + client.get_backup(request) @pytest.mark.parametrize( "request_type", [ - memorystore.GetBackupCollectionRequest, + memorystore.GetBackupRequest, dict, ], ) -def test_get_backup_collection_rest_call_success(request_type): +def test_get_backup_rest_call_success(request_type): client = MemorystoreClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding request_init = { - "name": "projects/sample1/locations/sample2/backupCollections/sample3" + "name": "projects/sample1/locations/sample2/backupCollections/sample3/backups/sample4" } request = request_type(**request_init) # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = memorystore.BackupCollection( + return_value = memorystore.Backup( name="name_value", - instance_uid="instance_uid_value", instance="instance_value", - kms_key="kms_key_value", + instance_uid="instance_uid_value", + total_size_bytes=1732, + engine_version="engine_version_value", + node_type=memorystore.Instance.NodeType.SHARED_CORE_NANO, + replica_count=1384, + shard_count=1178, + backup_type=memorystore.Backup.BackupType.ON_DEMAND, + state=memorystore.Backup.State.CREATING, uid="uid_value", - total_backup_size_bytes=2457, - total_backup_count=1921, ) # Wrap the value into a proper Response obj @@ -12586,26 +13881,30 @@ def test_get_backup_collection_rest_call_success(request_type): response_value.status_code = 200 # Convert return value to protobuf type - return_value = memorystore.BackupCollection.pb(return_value) + return_value = memorystore.Backup.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.get_backup_collection(request) + response = client.get_backup(request) # Establish that the response is the type that we expect. - assert isinstance(response, memorystore.BackupCollection) + assert isinstance(response, memorystore.Backup) assert response.name == "name_value" - assert response.instance_uid == "instance_uid_value" assert response.instance == "instance_value" - assert response.kms_key == "kms_key_value" + assert response.instance_uid == "instance_uid_value" + assert response.total_size_bytes == 1732 + assert response.engine_version == "engine_version_value" + assert response.node_type == memorystore.Instance.NodeType.SHARED_CORE_NANO + assert response.replica_count == 1384 + assert response.shard_count == 1178 + assert response.backup_type == memorystore.Backup.BackupType.ON_DEMAND + assert response.state == memorystore.Backup.State.CREATING assert response.uid == "uid_value" - assert response.total_backup_size_bytes == 2457 - assert response.total_backup_count == 1921 @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_backup_collection_rest_interceptors(null_interceptor): +def test_get_backup_rest_interceptors(null_interceptor): transport = transports.MemorystoreRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -12618,22 +13917,19 @@ def test_get_backup_collection_rest_interceptors(null_interceptor): mock.patch.object(type(client.transport._session), "request") as req, mock.patch.object(path_template, "transcode") as transcode, mock.patch.object( - transports.MemorystoreRestInterceptor, "post_get_backup_collection" + transports.MemorystoreRestInterceptor, "post_get_backup" ) as post, mock.patch.object( - transports.MemorystoreRestInterceptor, - "post_get_backup_collection_with_metadata", + transports.MemorystoreRestInterceptor, "post_get_backup_with_metadata" ) as post_with_metadata, mock.patch.object( - transports.MemorystoreRestInterceptor, "pre_get_backup_collection" + transports.MemorystoreRestInterceptor, "pre_get_backup" ) as pre, ): pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = memorystore.GetBackupCollectionRequest.pb( - memorystore.GetBackupCollectionRequest() - ) + pb_message = memorystore.GetBackupRequest.pb(memorystore.GetBackupRequest()) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -12644,21 +13940,19 @@ def test_get_backup_collection_rest_interceptors(null_interceptor): req.return_value = mock.Mock() req.return_value.status_code = 200 req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - return_value = memorystore.BackupCollection.to_json( - memorystore.BackupCollection() - ) + return_value = memorystore.Backup.to_json(memorystore.Backup()) req.return_value.content = return_value - request = memorystore.GetBackupCollectionRequest() + request = memorystore.GetBackupRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = memorystore.BackupCollection() - post_with_metadata.return_value = memorystore.BackupCollection(), metadata + post.return_value = memorystore.Backup() + post_with_metadata.return_value = memorystore.Backup(), metadata - client.get_backup_collection( + client.get_backup( request, metadata=[ ("key", "val"), @@ -12671,13 +13965,13 @@ def test_get_backup_collection_rest_interceptors(null_interceptor): post_with_metadata.assert_called_once() -def test_list_backups_rest_bad_request(request_type=memorystore.ListBackupsRequest): +def test_delete_backup_rest_bad_request(request_type=memorystore.DeleteBackupRequest): client = MemorystoreClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding request_init = { - "parent": "projects/sample1/locations/sample2/backupCollections/sample3" + "name": "projects/sample1/locations/sample2/backupCollections/sample3/backups/sample4" } request = request_type(**request_init) @@ -12694,55 +13988,47 @@ def test_list_backups_rest_bad_request(request_type=memorystore.ListBackupsReque response_value.request = mock.Mock() req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.list_backups(request) + client.delete_backup(request) @pytest.mark.parametrize( "request_type", [ - memorystore.ListBackupsRequest, + memorystore.DeleteBackupRequest, dict, ], ) -def test_list_backups_rest_call_success(request_type): +def test_delete_backup_rest_call_success(request_type): client = MemorystoreClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding request_init = { - "parent": "projects/sample1/locations/sample2/backupCollections/sample3" + "name": "projects/sample1/locations/sample2/backupCollections/sample3/backups/sample4" } request = request_type(**request_init) # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = memorystore.ListBackupsResponse( - next_page_token="next_page_token_value", - unreachable=["unreachable_value"], - ) + return_value = operations_pb2.Operation(name="operations/spam") # Wrap the value into a proper Response obj response_value = mock.Mock() response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = memorystore.ListBackupsResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.list_backups(request) + response = client.delete_backup(request) # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListBackupsPager) - assert response.next_page_token == "next_page_token_value" - assert response.unreachable == ["unreachable_value"] + json_return_value = json_format.MessageToJson(return_value) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_backups_rest_interceptors(null_interceptor): +def test_delete_backup_rest_interceptors(null_interceptor): transport = transports.MemorystoreRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -12754,20 +14040,23 @@ def test_list_backups_rest_interceptors(null_interceptor): with ( mock.patch.object(type(client.transport._session), "request") as req, mock.patch.object(path_template, "transcode") as transcode, + mock.patch.object(operation.Operation, "_set_result_from_operation"), mock.patch.object( - transports.MemorystoreRestInterceptor, "post_list_backups" + transports.MemorystoreRestInterceptor, "post_delete_backup" ) as post, mock.patch.object( - transports.MemorystoreRestInterceptor, "post_list_backups_with_metadata" + transports.MemorystoreRestInterceptor, "post_delete_backup_with_metadata" ) as post_with_metadata, mock.patch.object( - transports.MemorystoreRestInterceptor, "pre_list_backups" + transports.MemorystoreRestInterceptor, "pre_delete_backup" ) as pre, ): pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = memorystore.ListBackupsRequest.pb(memorystore.ListBackupsRequest()) + pb_message = memorystore.DeleteBackupRequest.pb( + memorystore.DeleteBackupRequest() + ) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -12778,21 +14067,19 @@ def test_list_backups_rest_interceptors(null_interceptor): req.return_value = mock.Mock() req.return_value.status_code = 200 req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - return_value = memorystore.ListBackupsResponse.to_json( - memorystore.ListBackupsResponse() - ) + return_value = json_format.MessageToJson(operations_pb2.Operation()) req.return_value.content = return_value - request = memorystore.ListBackupsRequest() + request = memorystore.DeleteBackupRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = memorystore.ListBackupsResponse() - post_with_metadata.return_value = memorystore.ListBackupsResponse(), metadata + post.return_value = operations_pb2.Operation() + post_with_metadata.return_value = operations_pb2.Operation(), metadata - client.list_backups( + client.delete_backup( request, metadata=[ ("key", "val"), @@ -12805,7 +14092,7 @@ def test_list_backups_rest_interceptors(null_interceptor): post_with_metadata.assert_called_once() -def test_get_backup_rest_bad_request(request_type=memorystore.GetBackupRequest): +def test_export_backup_rest_bad_request(request_type=memorystore.ExportBackupRequest): client = MemorystoreClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) @@ -12828,17 +14115,17 @@ def test_get_backup_rest_bad_request(request_type=memorystore.GetBackupRequest): response_value.request = mock.Mock() req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.get_backup(request) + client.export_backup(request) @pytest.mark.parametrize( "request_type", [ - memorystore.GetBackupRequest, + memorystore.ExportBackupRequest, dict, ], ) -def test_get_backup_rest_call_success(request_type): +def test_export_backup_rest_call_success(request_type): client = MemorystoreClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) @@ -12852,49 +14139,23 @@ def test_get_backup_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 = memorystore.Backup( - name="name_value", - instance="instance_value", - instance_uid="instance_uid_value", - total_size_bytes=1732, - engine_version="engine_version_value", - node_type=memorystore.Instance.NodeType.SHARED_CORE_NANO, - replica_count=1384, - shard_count=1178, - backup_type=memorystore.Backup.BackupType.ON_DEMAND, - state=memorystore.Backup.State.CREATING, - uid="uid_value", - ) + return_value = operations_pb2.Operation(name="operations/spam") # Wrap the value into a proper Response obj response_value = mock.Mock() response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = memorystore.Backup.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.get_backup(request) + response = client.export_backup(request) # Establish that the response is the type that we expect. - assert isinstance(response, memorystore.Backup) - assert response.name == "name_value" - assert response.instance == "instance_value" - assert response.instance_uid == "instance_uid_value" - assert response.total_size_bytes == 1732 - assert response.engine_version == "engine_version_value" - assert response.node_type == memorystore.Instance.NodeType.SHARED_CORE_NANO - assert response.replica_count == 1384 - assert response.shard_count == 1178 - assert response.backup_type == memorystore.Backup.BackupType.ON_DEMAND - assert response.state == memorystore.Backup.State.CREATING - assert response.uid == "uid_value" + json_return_value = json_format.MessageToJson(return_value) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_backup_rest_interceptors(null_interceptor): +def test_export_backup_rest_interceptors(null_interceptor): transport = transports.MemorystoreRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -12906,20 +14167,23 @@ def test_get_backup_rest_interceptors(null_interceptor): with ( mock.patch.object(type(client.transport._session), "request") as req, mock.patch.object(path_template, "transcode") as transcode, + mock.patch.object(operation.Operation, "_set_result_from_operation"), mock.patch.object( - transports.MemorystoreRestInterceptor, "post_get_backup" + transports.MemorystoreRestInterceptor, "post_export_backup" ) as post, mock.patch.object( - transports.MemorystoreRestInterceptor, "post_get_backup_with_metadata" + transports.MemorystoreRestInterceptor, "post_export_backup_with_metadata" ) as post_with_metadata, mock.patch.object( - transports.MemorystoreRestInterceptor, "pre_get_backup" + transports.MemorystoreRestInterceptor, "pre_export_backup" ) as pre, ): pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = memorystore.GetBackupRequest.pb(memorystore.GetBackupRequest()) + pb_message = memorystore.ExportBackupRequest.pb( + memorystore.ExportBackupRequest() + ) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -12930,19 +14194,19 @@ def test_get_backup_rest_interceptors(null_interceptor): req.return_value = mock.Mock() req.return_value.status_code = 200 req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - return_value = memorystore.Backup.to_json(memorystore.Backup()) + return_value = json_format.MessageToJson(operations_pb2.Operation()) req.return_value.content = return_value - request = memorystore.GetBackupRequest() + request = memorystore.ExportBackupRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = memorystore.Backup() - post_with_metadata.return_value = memorystore.Backup(), metadata + post.return_value = operations_pb2.Operation() + post_with_metadata.return_value = operations_pb2.Operation(), metadata - client.get_backup( + client.export_backup( request, metadata=[ ("key", "val"), @@ -12955,14 +14219,14 @@ def test_get_backup_rest_interceptors(null_interceptor): post_with_metadata.assert_called_once() -def test_delete_backup_rest_bad_request(request_type=memorystore.DeleteBackupRequest): +def test_backup_instance_rest_bad_request( + request_type=memorystore.BackupInstanceRequest, +): client = MemorystoreClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = { - "name": "projects/sample1/locations/sample2/backupCollections/sample3/backups/sample4" - } + request_init = {"name": "projects/sample1/locations/sample2/instances/sample3"} request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -12978,25 +14242,23 @@ def test_delete_backup_rest_bad_request(request_type=memorystore.DeleteBackupReq response_value.request = mock.Mock() req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.delete_backup(request) + client.backup_instance(request) @pytest.mark.parametrize( "request_type", [ - memorystore.DeleteBackupRequest, + memorystore.BackupInstanceRequest, dict, ], ) -def test_delete_backup_rest_call_success(request_type): +def test_backup_instance_rest_call_success(request_type): client = MemorystoreClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = { - "name": "projects/sample1/locations/sample2/backupCollections/sample3/backups/sample4" - } + request_init = {"name": "projects/sample1/locations/sample2/instances/sample3"} request = request_type(**request_init) # Mock the http request call within the method and fake a response. @@ -13011,14 +14273,14 @@ def test_delete_backup_rest_call_success(request_type): response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.delete_backup(request) + response = client.backup_instance(request) # Establish that the response is the type that we expect. json_return_value = json_format.MessageToJson(return_value) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_delete_backup_rest_interceptors(null_interceptor): +def test_backup_instance_rest_interceptors(null_interceptor): transport = transports.MemorystoreRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -13032,20 +14294,20 @@ def test_delete_backup_rest_interceptors(null_interceptor): mock.patch.object(path_template, "transcode") as transcode, mock.patch.object(operation.Operation, "_set_result_from_operation"), mock.patch.object( - transports.MemorystoreRestInterceptor, "post_delete_backup" + transports.MemorystoreRestInterceptor, "post_backup_instance" ) as post, mock.patch.object( - transports.MemorystoreRestInterceptor, "post_delete_backup_with_metadata" + transports.MemorystoreRestInterceptor, "post_backup_instance_with_metadata" ) as post_with_metadata, mock.patch.object( - transports.MemorystoreRestInterceptor, "pre_delete_backup" + transports.MemorystoreRestInterceptor, "pre_backup_instance" ) as pre, ): pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = memorystore.DeleteBackupRequest.pb( - memorystore.DeleteBackupRequest() + pb_message = memorystore.BackupInstanceRequest.pb( + memorystore.BackupInstanceRequest() ) transcode.return_value = { "method": "post", @@ -13060,7 +14322,7 @@ def test_delete_backup_rest_interceptors(null_interceptor): return_value = json_format.MessageToJson(operations_pb2.Operation()) req.return_value.content = return_value - request = memorystore.DeleteBackupRequest() + request = memorystore.BackupInstanceRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), @@ -13069,7 +14331,7 @@ def test_delete_backup_rest_interceptors(null_interceptor): post.return_value = operations_pb2.Operation() post_with_metadata.return_value = operations_pb2.Operation(), metadata - client.delete_backup( + client.backup_instance( request, metadata=[ ("key", "val"), @@ -13082,14 +14344,14 @@ def test_delete_backup_rest_interceptors(null_interceptor): post_with_metadata.assert_called_once() -def test_export_backup_rest_bad_request(request_type=memorystore.ExportBackupRequest): +def test_start_migration_rest_bad_request( + request_type=memorystore.StartMigrationRequest, +): client = MemorystoreClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = { - "name": "projects/sample1/locations/sample2/backupCollections/sample3/backups/sample4" - } + request_init = {"name": "projects/sample1/locations/sample2/instances/sample3"} request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -13105,25 +14367,23 @@ def test_export_backup_rest_bad_request(request_type=memorystore.ExportBackupReq response_value.request = mock.Mock() req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.export_backup(request) + client.start_migration(request) @pytest.mark.parametrize( "request_type", [ - memorystore.ExportBackupRequest, + memorystore.StartMigrationRequest, dict, ], ) -def test_export_backup_rest_call_success(request_type): +def test_start_migration_rest_call_success(request_type): client = MemorystoreClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = { - "name": "projects/sample1/locations/sample2/backupCollections/sample3/backups/sample4" - } + request_init = {"name": "projects/sample1/locations/sample2/instances/sample3"} request = request_type(**request_init) # Mock the http request call within the method and fake a response. @@ -13138,14 +14398,14 @@ def test_export_backup_rest_call_success(request_type): response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.export_backup(request) + response = client.start_migration(request) # Establish that the response is the type that we expect. json_return_value = json_format.MessageToJson(return_value) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_export_backup_rest_interceptors(null_interceptor): +def test_start_migration_rest_interceptors(null_interceptor): transport = transports.MemorystoreRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -13159,20 +14419,20 @@ def test_export_backup_rest_interceptors(null_interceptor): mock.patch.object(path_template, "transcode") as transcode, mock.patch.object(operation.Operation, "_set_result_from_operation"), mock.patch.object( - transports.MemorystoreRestInterceptor, "post_export_backup" + transports.MemorystoreRestInterceptor, "post_start_migration" ) as post, mock.patch.object( - transports.MemorystoreRestInterceptor, "post_export_backup_with_metadata" + transports.MemorystoreRestInterceptor, "post_start_migration_with_metadata" ) as post_with_metadata, mock.patch.object( - transports.MemorystoreRestInterceptor, "pre_export_backup" + transports.MemorystoreRestInterceptor, "pre_start_migration" ) as pre, ): pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = memorystore.ExportBackupRequest.pb( - memorystore.ExportBackupRequest() + pb_message = memorystore.StartMigrationRequest.pb( + memorystore.StartMigrationRequest() ) transcode.return_value = { "method": "post", @@ -13187,7 +14447,7 @@ def test_export_backup_rest_interceptors(null_interceptor): return_value = json_format.MessageToJson(operations_pb2.Operation()) req.return_value.content = return_value - request = memorystore.ExportBackupRequest() + request = memorystore.StartMigrationRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), @@ -13196,7 +14456,7 @@ def test_export_backup_rest_interceptors(null_interceptor): post.return_value = operations_pb2.Operation() post_with_metadata.return_value = operations_pb2.Operation(), metadata - client.export_backup( + client.start_migration( request, metadata=[ ("key", "val"), @@ -13209,8 +14469,8 @@ def test_export_backup_rest_interceptors(null_interceptor): post_with_metadata.assert_called_once() -def test_backup_instance_rest_bad_request( - request_type=memorystore.BackupInstanceRequest, +def test_finish_migration_rest_bad_request( + request_type=memorystore.FinishMigrationRequest, ): client = MemorystoreClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" @@ -13232,17 +14492,17 @@ def test_backup_instance_rest_bad_request( response_value.request = mock.Mock() req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.backup_instance(request) + client.finish_migration(request) @pytest.mark.parametrize( "request_type", [ - memorystore.BackupInstanceRequest, + memorystore.FinishMigrationRequest, dict, ], ) -def test_backup_instance_rest_call_success(request_type): +def test_finish_migration_rest_call_success(request_type): client = MemorystoreClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) @@ -13263,14 +14523,14 @@ def test_backup_instance_rest_call_success(request_type): response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.backup_instance(request) + response = client.finish_migration(request) # Establish that the response is the type that we expect. json_return_value = json_format.MessageToJson(return_value) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_backup_instance_rest_interceptors(null_interceptor): +def test_finish_migration_rest_interceptors(null_interceptor): transport = transports.MemorystoreRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -13284,20 +14544,20 @@ def test_backup_instance_rest_interceptors(null_interceptor): mock.patch.object(path_template, "transcode") as transcode, mock.patch.object(operation.Operation, "_set_result_from_operation"), mock.patch.object( - transports.MemorystoreRestInterceptor, "post_backup_instance" + transports.MemorystoreRestInterceptor, "post_finish_migration" ) as post, mock.patch.object( - transports.MemorystoreRestInterceptor, "post_backup_instance_with_metadata" + transports.MemorystoreRestInterceptor, "post_finish_migration_with_metadata" ) as post_with_metadata, mock.patch.object( - transports.MemorystoreRestInterceptor, "pre_backup_instance" + transports.MemorystoreRestInterceptor, "pre_finish_migration" ) as pre, ): pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = memorystore.BackupInstanceRequest.pb( - memorystore.BackupInstanceRequest() + pb_message = memorystore.FinishMigrationRequest.pb( + memorystore.FinishMigrationRequest() ) transcode.return_value = { "method": "post", @@ -13312,7 +14572,7 @@ def test_backup_instance_rest_interceptors(null_interceptor): return_value = json_format.MessageToJson(operations_pb2.Operation()) req.return_value.content = return_value - request = memorystore.BackupInstanceRequest() + request = memorystore.FinishMigrationRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), @@ -13321,7 +14581,7 @@ def test_backup_instance_rest_interceptors(null_interceptor): post.return_value = operations_pb2.Operation() post_with_metadata.return_value = operations_pb2.Operation(), metadata - client.backup_instance( + client.finish_migration( request, metadata=[ ("key", "val"), @@ -14010,6 +15270,44 @@ def test_backup_instance_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_start_migration_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.start_migration), "__call__") as call: + client.start_migration(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = memorystore.StartMigrationRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_finish_migration_empty_call_rest(): + client = MemorystoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.finish_migration), "__call__") as call: + client.finish_migration(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = memorystore.FinishMigrationRequest() + assert args[0] == request_msg + + def test_memorystore_rest_lro_client(): client = MemorystoreClient( credentials=ga_credentials.AnonymousCredentials(), @@ -14075,6 +15373,8 @@ def test_memorystore_base_transport(): "delete_backup", "export_backup", "backup_instance", + "start_migration", + "finish_migration", "get_location", "list_locations", "get_operation", @@ -14122,7 +15422,11 @@ def test_memorystore_base_transport_with_credentials_file(): load_creds.assert_called_once_with( "credentials.json", scopes=None, - default_scopes=("https://www.googleapis.com/auth/cloud-platform",), + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/memorystore.read-only", + "https://www.googleapis.com/auth/memorystore.read-write", + ), quota_project_id="octopus", ) @@ -14148,7 +15452,11 @@ def test_memorystore_auth_adc(): MemorystoreClient() adc.assert_called_once_with( scopes=None, - default_scopes=("https://www.googleapis.com/auth/cloud-platform",), + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/memorystore.read-only", + "https://www.googleapis.com/auth/memorystore.read-write", + ), quota_project_id=None, ) @@ -14168,7 +15476,11 @@ def test_memorystore_transport_auth_adc(transport_class): transport_class(quota_project_id="octopus", scopes=["1", "2"]) adc.assert_called_once_with( scopes=["1", "2"], - default_scopes=("https://www.googleapis.com/auth/cloud-platform",), + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/memorystore.read-only", + "https://www.googleapis.com/auth/memorystore.read-write", + ), quota_project_id="octopus", ) @@ -14221,7 +15533,11 @@ def test_memorystore_transport_create_channel(transport_class, grpc_helpers): credentials=creds, credentials_file=None, quota_project_id="octopus", - default_scopes=("https://www.googleapis.com/auth/cloud-platform",), + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/memorystore.read-only", + "https://www.googleapis.com/auth/memorystore.read-write", + ), scopes=["1", "2"], default_host="memorystore.googleapis.com", ssl_credentials=None, @@ -14393,6 +15709,12 @@ def test_memorystore_client_transport_session_collision(transport_name): session1 = client1.transport.backup_instance._session session2 = client2.transport.backup_instance._session assert session1 != session2 + session1 = client1.transport.start_migration._session + session2 = client2.transport.start_migration._session + assert session1 != session2 + session1 = client1.transport.finish_migration._session + session2 = client2.transport.finish_migration._session + assert session1 != session2 def test_memorystore_grpc_transport_channel(): @@ -14797,10 +16119,38 @@ def test_parse_network_path(): assert expected == actual -def test_service_attachment_path(): +def test_network_attachment_path(): project = "squid" region = "clam" - service_attachment = "whelk" + network_attachment = "whelk" + expected = "projects/{project}/regions/{region}/networkAttachments/{network_attachment}".format( + project=project, + region=region, + network_attachment=network_attachment, + ) + actual = MemorystoreClient.network_attachment_path( + project, region, network_attachment + ) + assert expected == actual + + +def test_parse_network_attachment_path(): + expected = { + "project": "octopus", + "region": "oyster", + "network_attachment": "nudibranch", + } + path = MemorystoreClient.network_attachment_path(**expected) + + # Check that the path construction is reversible. + actual = MemorystoreClient.parse_network_attachment_path(path) + assert expected == actual + + +def test_service_attachment_path(): + project = "cuttlefish" + region = "mussel" + service_attachment = "winkle" expected = "projects/{project}/regions/{region}/serviceAttachments/{service_attachment}".format( project=project, region=region, @@ -14814,9 +16164,9 @@ def test_service_attachment_path(): def test_parse_service_attachment_path(): expected = { - "project": "octopus", - "region": "oyster", - "service_attachment": "nudibranch", + "project": "nautilus", + "region": "scallop", + "service_attachment": "abalone", } path = MemorystoreClient.service_attachment_path(**expected) @@ -14826,8 +16176,8 @@ def test_parse_service_attachment_path(): def test_shared_regional_certificate_authority_path(): - project = "cuttlefish" - location = "mussel" + project = "squid" + location = "clam" expected = "projects/{project}/locations/{location}/sharedRegionalCertificateAuthority".format( project=project, location=location, @@ -14840,8 +16190,8 @@ def test_shared_regional_certificate_authority_path(): def test_parse_shared_regional_certificate_authority_path(): expected = { - "project": "winkle", - "location": "nautilus", + "project": "whelk", + "location": "octopus", } path = MemorystoreClient.shared_regional_certificate_authority_path(**expected) @@ -14851,7 +16201,7 @@ def test_parse_shared_regional_certificate_authority_path(): def test_common_billing_account_path(): - billing_account = "scallop" + billing_account = "oyster" expected = "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -14861,7 +16211,7 @@ def test_common_billing_account_path(): def test_parse_common_billing_account_path(): expected = { - "billing_account": "abalone", + "billing_account": "nudibranch", } path = MemorystoreClient.common_billing_account_path(**expected) @@ -14871,7 +16221,7 @@ def test_parse_common_billing_account_path(): def test_common_folder_path(): - folder = "squid" + folder = "cuttlefish" expected = "folders/{folder}".format( folder=folder, ) @@ -14881,7 +16231,7 @@ def test_common_folder_path(): def test_parse_common_folder_path(): expected = { - "folder": "clam", + "folder": "mussel", } path = MemorystoreClient.common_folder_path(**expected) @@ -14891,7 +16241,7 @@ def test_parse_common_folder_path(): def test_common_organization_path(): - organization = "whelk" + organization = "winkle" expected = "organizations/{organization}".format( organization=organization, ) @@ -14901,7 +16251,7 @@ def test_common_organization_path(): def test_parse_common_organization_path(): expected = { - "organization": "octopus", + "organization": "nautilus", } path = MemorystoreClient.common_organization_path(**expected) @@ -14911,7 +16261,7 @@ def test_parse_common_organization_path(): def test_common_project_path(): - project = "oyster" + project = "scallop" expected = "projects/{project}".format( project=project, ) @@ -14921,7 +16271,7 @@ def test_common_project_path(): def test_parse_common_project_path(): expected = { - "project": "nudibranch", + "project": "abalone", } path = MemorystoreClient.common_project_path(**expected) @@ -14931,8 +16281,8 @@ def test_parse_common_project_path(): def test_common_location_path(): - project = "cuttlefish" - location = "mussel" + project = "squid" + location = "clam" expected = "projects/{project}/locations/{location}".format( project=project, location=location, @@ -14943,8 +16293,8 @@ def test_common_location_path(): def test_parse_common_location_path(): expected = { - "project": "winkle", - "location": "nautilus", + "project": "whelk", + "location": "octopus", } path = MemorystoreClient.common_location_path(**expected) diff --git a/packages/google-devicesandservices-health/google/devicesandservices/health_v4/types/data_subscription_service.py b/packages/google-devicesandservices-health/google/devicesandservices/health_v4/types/data_subscription_service.py index 9d82c528389a..d60e5923befd 100644 --- a/packages/google-devicesandservices-health/google/devicesandservices/health_v4/types/data_subscription_service.py +++ b/packages/google-devicesandservices-health/google/devicesandservices/health_v4/types/data_subscription_service.py @@ -588,10 +588,11 @@ class SubscriptionCreatePolicy(proto.Enum): class EndpointAuthorization(proto.Message): r"""Authorization mechanism for a subscriber endpoint. For all requests sent by the Webhooks service, the JSON payload is cryptographically - signed. The signature is delivered in the ``X-HEALTHAPI-SIGNATURE`` - HTTP header. This is an ECDSA (NIST P256) signature of the JSON - payload. Clients must verify this signature using Google Health - API's public key to confirm the payload was sent by the Health API. + signed. The signature is delivered in the + ``GOOGLE-HEALTH-API-SIGNATURE`` HTTP header. This is an ECDSA (NIST + P256) signature of the JSON payload. Clients must verify this + signature using Google Health API's public key to confirm the + payload was sent by the Health API. Attributes: secret (str):