diff --git a/packages/google-cloud-video-live-stream/google/cloud/video/live_stream/__init__.py b/packages/google-cloud-video-live-stream/google/cloud/video/live_stream/__init__.py index da5adba35143..29105de674f2 100644 --- a/packages/google-cloud-video-live-stream/google/cloud/video/live_stream/__init__.py +++ b/packages/google-cloud-video-live-stream/google/cloud/video/live_stream/__init__.py @@ -42,6 +42,7 @@ AudioStreamProperty, Channel, Clip, + DvrSession, Encryption, Event, Input, @@ -54,6 +55,7 @@ Pool, RetentionConfig, StaticOverlay, + TimeInterval, VideoFormat, VideoStreamProperty, ) @@ -62,16 +64,19 @@ CreateAssetRequest, CreateChannelRequest, CreateClipRequest, + CreateDvrSessionRequest, CreateEventRequest, CreateInputRequest, DeleteAssetRequest, DeleteChannelRequest, DeleteClipRequest, + DeleteDvrSessionRequest, DeleteEventRequest, DeleteInputRequest, GetAssetRequest, GetChannelRequest, GetClipRequest, + GetDvrSessionRequest, GetEventRequest, GetInputRequest, GetPoolRequest, @@ -81,6 +86,8 @@ ListChannelsResponse, ListClipsRequest, ListClipsResponse, + ListDvrSessionsRequest, + ListDvrSessionsResponse, ListEventsRequest, ListEventsResponse, ListInputsRequest, @@ -89,6 +96,7 @@ StartChannelRequest, StopChannelRequest, UpdateChannelRequest, + UpdateDvrSessionRequest, UpdateInputRequest, UpdatePoolRequest, ) @@ -111,6 +119,7 @@ "AudioStreamProperty", "Channel", "Clip", + "DvrSession", "Encryption", "Event", "Input", @@ -123,22 +132,26 @@ "Pool", "RetentionConfig", "StaticOverlay", + "TimeInterval", "VideoFormat", "VideoStreamProperty", "ChannelOperationResponse", "CreateAssetRequest", "CreateChannelRequest", "CreateClipRequest", + "CreateDvrSessionRequest", "CreateEventRequest", "CreateInputRequest", "DeleteAssetRequest", "DeleteChannelRequest", "DeleteClipRequest", + "DeleteDvrSessionRequest", "DeleteEventRequest", "DeleteInputRequest", "GetAssetRequest", "GetChannelRequest", "GetClipRequest", + "GetDvrSessionRequest", "GetEventRequest", "GetInputRequest", "GetPoolRequest", @@ -148,6 +161,8 @@ "ListChannelsResponse", "ListClipsRequest", "ListClipsResponse", + "ListDvrSessionsRequest", + "ListDvrSessionsResponse", "ListEventsRequest", "ListEventsResponse", "ListInputsRequest", @@ -156,6 +171,7 @@ "StartChannelRequest", "StopChannelRequest", "UpdateChannelRequest", + "UpdateDvrSessionRequest", "UpdateInputRequest", "UpdatePoolRequest", ) diff --git a/packages/google-cloud-video-live-stream/google/cloud/video/live_stream_v1/__init__.py b/packages/google-cloud-video-live-stream/google/cloud/video/live_stream_v1/__init__.py index 5e0d8ec73541..b4011c0a5a56 100644 --- a/packages/google-cloud-video-live-stream/google/cloud/video/live_stream_v1/__init__.py +++ b/packages/google-cloud-video-live-stream/google/cloud/video/live_stream_v1/__init__.py @@ -40,6 +40,7 @@ AudioStreamProperty, Channel, Clip, + DvrSession, Encryption, Event, Input, @@ -52,6 +53,7 @@ Pool, RetentionConfig, StaticOverlay, + TimeInterval, VideoFormat, VideoStreamProperty, ) @@ -60,16 +62,19 @@ CreateAssetRequest, CreateChannelRequest, CreateClipRequest, + CreateDvrSessionRequest, CreateEventRequest, CreateInputRequest, DeleteAssetRequest, DeleteChannelRequest, DeleteClipRequest, + DeleteDvrSessionRequest, DeleteEventRequest, DeleteInputRequest, GetAssetRequest, GetChannelRequest, GetClipRequest, + GetDvrSessionRequest, GetEventRequest, GetInputRequest, GetPoolRequest, @@ -79,6 +84,8 @@ ListChannelsResponse, ListClipsRequest, ListClipsResponse, + ListDvrSessionsRequest, + ListDvrSessionsResponse, ListEventsRequest, ListEventsResponse, ListInputsRequest, @@ -87,6 +94,7 @@ StartChannelRequest, StopChannelRequest, UpdateChannelRequest, + UpdateDvrSessionRequest, UpdateInputRequest, UpdatePoolRequest, ) @@ -103,19 +111,23 @@ "CreateAssetRequest", "CreateChannelRequest", "CreateClipRequest", + "CreateDvrSessionRequest", "CreateEventRequest", "CreateInputRequest", "DeleteAssetRequest", "DeleteChannelRequest", "DeleteClipRequest", + "DeleteDvrSessionRequest", "DeleteEventRequest", "DeleteInputRequest", + "DvrSession", "ElementaryStream", "Encryption", "Event", "GetAssetRequest", "GetChannelRequest", "GetClipRequest", + "GetDvrSessionRequest", "GetEventRequest", "GetInputRequest", "GetPoolRequest", @@ -129,6 +141,8 @@ "ListChannelsResponse", "ListClipsRequest", "ListClipsResponse", + "ListDvrSessionsRequest", + "ListDvrSessionsResponse", "ListEventsRequest", "ListEventsResponse", "ListInputsRequest", @@ -149,8 +163,10 @@ "StaticOverlay", "StopChannelRequest", "TextStream", + "TimeInterval", "TimecodeConfig", "UpdateChannelRequest", + "UpdateDvrSessionRequest", "UpdateInputRequest", "UpdatePoolRequest", "VideoFormat", diff --git a/packages/google-cloud-video-live-stream/google/cloud/video/live_stream_v1/gapic_metadata.json b/packages/google-cloud-video-live-stream/google/cloud/video/live_stream_v1/gapic_metadata.json index e18d784d65b9..d94a38f317f9 100644 --- a/packages/google-cloud-video-live-stream/google/cloud/video/live_stream_v1/gapic_metadata.json +++ b/packages/google-cloud-video-live-stream/google/cloud/video/live_stream_v1/gapic_metadata.json @@ -25,6 +25,11 @@ "create_clip" ] }, + "CreateDvrSession": { + "methods": [ + "create_dvr_session" + ] + }, "CreateEvent": { "methods": [ "create_event" @@ -50,6 +55,11 @@ "delete_clip" ] }, + "DeleteDvrSession": { + "methods": [ + "delete_dvr_session" + ] + }, "DeleteEvent": { "methods": [ "delete_event" @@ -75,6 +85,11 @@ "get_clip" ] }, + "GetDvrSession": { + "methods": [ + "get_dvr_session" + ] + }, "GetEvent": { "methods": [ "get_event" @@ -105,6 +120,11 @@ "list_clips" ] }, + "ListDvrSessions": { + "methods": [ + "list_dvr_sessions" + ] + }, "ListEvents": { "methods": [ "list_events" @@ -130,6 +150,11 @@ "update_channel" ] }, + "UpdateDvrSession": { + "methods": [ + "update_dvr_session" + ] + }, "UpdateInput": { "methods": [ "update_input" @@ -160,6 +185,11 @@ "create_clip" ] }, + "CreateDvrSession": { + "methods": [ + "create_dvr_session" + ] + }, "CreateEvent": { "methods": [ "create_event" @@ -185,6 +215,11 @@ "delete_clip" ] }, + "DeleteDvrSession": { + "methods": [ + "delete_dvr_session" + ] + }, "DeleteEvent": { "methods": [ "delete_event" @@ -210,6 +245,11 @@ "get_clip" ] }, + "GetDvrSession": { + "methods": [ + "get_dvr_session" + ] + }, "GetEvent": { "methods": [ "get_event" @@ -240,6 +280,11 @@ "list_clips" ] }, + "ListDvrSessions": { + "methods": [ + "list_dvr_sessions" + ] + }, "ListEvents": { "methods": [ "list_events" @@ -265,6 +310,11 @@ "update_channel" ] }, + "UpdateDvrSession": { + "methods": [ + "update_dvr_session" + ] + }, "UpdateInput": { "methods": [ "update_input" @@ -295,6 +345,11 @@ "create_clip" ] }, + "CreateDvrSession": { + "methods": [ + "create_dvr_session" + ] + }, "CreateEvent": { "methods": [ "create_event" @@ -320,6 +375,11 @@ "delete_clip" ] }, + "DeleteDvrSession": { + "methods": [ + "delete_dvr_session" + ] + }, "DeleteEvent": { "methods": [ "delete_event" @@ -345,6 +405,11 @@ "get_clip" ] }, + "GetDvrSession": { + "methods": [ + "get_dvr_session" + ] + }, "GetEvent": { "methods": [ "get_event" @@ -375,6 +440,11 @@ "list_clips" ] }, + "ListDvrSessions": { + "methods": [ + "list_dvr_sessions" + ] + }, "ListEvents": { "methods": [ "list_events" @@ -400,6 +470,11 @@ "update_channel" ] }, + "UpdateDvrSession": { + "methods": [ + "update_dvr_session" + ] + }, "UpdateInput": { "methods": [ "update_input" diff --git a/packages/google-cloud-video-live-stream/google/cloud/video/live_stream_v1/services/livestream_service/async_client.py b/packages/google-cloud-video-live-stream/google/cloud/video/live_stream_v1/services/livestream_service/async_client.py index 8d252eae548f..e0b9e9c04217 100644 --- a/packages/google-cloud-video-live-stream/google/cloud/video/live_stream_v1/services/livestream_service/async_client.py +++ b/packages/google-cloud-video-live-stream/google/cloud/video/live_stream_v1/services/livestream_service/async_client.py @@ -94,6 +94,10 @@ class LivestreamServiceAsyncClient: parse_channel_path = staticmethod(LivestreamServiceClient.parse_channel_path) clip_path = staticmethod(LivestreamServiceClient.clip_path) parse_clip_path = staticmethod(LivestreamServiceClient.parse_clip_path) + dvr_session_path = staticmethod(LivestreamServiceClient.dvr_session_path) + parse_dvr_session_path = staticmethod( + LivestreamServiceClient.parse_dvr_session_path + ) event_path = staticmethod(LivestreamServiceClient.event_path) parse_event_path = staticmethod(LivestreamServiceClient.parse_event_path) input_path = staticmethod(LivestreamServiceClient.input_path) @@ -1852,6 +1856,7 @@ async def sample_update_input(): overwritten in the Input resource by the update. You can only update the following fields: + - ```tier`` `__ - ```preprocessingConfig`` `__ - ```securityRules`` `__ @@ -2828,7 +2833,7 @@ async def delete_clip( ) -> operation_async.AsyncOperation: r"""Deletes the specified clip job resource. This method only deletes the clip job and does not delete the VOD - clip stored in the GCS. + clip stored in Cloud Storage. .. code-block:: python @@ -2952,6 +2957,684 @@ async def sample_delete_clip(): # Done; return the response. return response + async def create_dvr_session( + self, + request: Optional[Union[service.CreateDvrSessionRequest, dict]] = None, + *, + parent: Optional[str] = None, + dvr_session: Optional[resources.DvrSession] = None, + dvr_session_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation_async.AsyncOperation: + r"""Creates a DVR session with the provided unique ID in + the specified channel. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud.video import live_stream_v1 + + async def sample_create_dvr_session(): + # Create a client + client = live_stream_v1.LivestreamServiceAsyncClient() + + # Initialize request argument(s) + dvr_session = live_stream_v1.DvrSession() + dvr_session.dvr_manifests.manifest_key = "manifest_key_value" + + request = live_stream_v1.CreateDvrSessionRequest( + parent="parent_value", + dvr_session_id="dvr_session_id_value", + dvr_session=dvr_session, + ) + + # Make the request + operation = client.create_dvr_session(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.video.live_stream_v1.types.CreateDvrSessionRequest, dict]]): + The request object. Request message for + "LivestreamService.CreateDvrSession". + parent (:class:`str`): + Required. The parent resource name, in the following + form: + ``projects/{project}/locations/{location}/channels/{channelId}``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + dvr_session (:class:`google.cloud.video.live_stream_v1.types.DvrSession`): + Required. The resource being created + This corresponds to the ``dvr_session`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + dvr_session_id (:class:`str`): + Required. Id of the requesting object + in the following form: + + 1. 1 character minimum, 63 characters + maximum + 2. Only contains letters, digits, + underscores, and hyphens + + This corresponds to the ``dvr_session_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.video.live_stream_v1.types.DvrSession` DvrSession is a sub-resource under channel. Each DvrSession represents a DVR + recording of the live stream for a specific time + range. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent, dvr_session, dvr_session_id] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, service.CreateDvrSessionRequest): + request = service.CreateDvrSessionRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if dvr_session is not None: + request.dvr_session = dvr_session + if dvr_session_id is not None: + request.dvr_session_id = dvr_session_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.create_dvr_session + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + resources.DvrSession, + metadata_type=service.OperationMetadata, + ) + + # Done; return the response. + return response + + async def list_dvr_sessions( + self, + request: Optional[Union[service.ListDvrSessionsRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListDvrSessionsAsyncPager: + r"""Returns a list of all DVR sessions in the specified + channel. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud.video import live_stream_v1 + + async def sample_list_dvr_sessions(): + # Create a client + client = live_stream_v1.LivestreamServiceAsyncClient() + + # Initialize request argument(s) + request = live_stream_v1.ListDvrSessionsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_dvr_sessions(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.video.live_stream_v1.types.ListDvrSessionsRequest, dict]]): + The request object. Request message for + "LivestreamService.ListDvrSessions". + parent (:class:`str`): + Required. Parent value for + ListDvrSessionsRequest + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.video.live_stream_v1.services.livestream_service.pagers.ListDvrSessionsAsyncPager: + Response message for + "LivestreamService.ListDvrSessions". + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, service.ListDvrSessionsRequest): + request = service.ListDvrSessionsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.list_dvr_sessions + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListDvrSessionsAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_dvr_session( + self, + request: Optional[Union[service.GetDvrSessionRequest, 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]]] = (), + ) -> resources.DvrSession: + r"""Returns the specified DVR session. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud.video import live_stream_v1 + + async def sample_get_dvr_session(): + # Create a client + client = live_stream_v1.LivestreamServiceAsyncClient() + + # Initialize request argument(s) + request = live_stream_v1.GetDvrSessionRequest( + name="name_value", + ) + + # Make the request + response = await client.get_dvr_session(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.video.live_stream_v1.types.GetDvrSessionRequest, dict]]): + The request object. Request message for + "LivestreamService.GetDvrSession". + name (:class:`str`): + Required. Name of the resource, in the following form: + ``projects/{project}/locations/{location}/channels/{channelId}/dvrSessions/{dvrSessionId}``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.video.live_stream_v1.types.DvrSession: + DvrSession is a sub-resource under + channel. Each DvrSession represents a + DVR recording of the live stream for a + specific time range. + + """ + # Create or coerce a protobuf request 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, service.GetDvrSessionRequest): + request = service.GetDvrSessionRequest(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_dvr_session + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def delete_dvr_session( + self, + request: Optional[Union[service.DeleteDvrSessionRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation_async.AsyncOperation: + r"""Deletes the specified DVR session. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud.video import live_stream_v1 + + async def sample_delete_dvr_session(): + # Create a client + client = live_stream_v1.LivestreamServiceAsyncClient() + + # Initialize request argument(s) + request = live_stream_v1.DeleteDvrSessionRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_dvr_session(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.video.live_stream_v1.types.DeleteDvrSessionRequest, dict]]): + The request object. Request message for + "LivestreamService.DeleteDvrSession". + name (:class:`str`): + Required. The name of the event resource, in the form + of: + ``projects/{project}/locations/{location}/channels/{channelId}/dvrSessions/{dvrSessionId}``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated + empty messages in your APIs. A typical example is to + use it as the request or the response type of an API + method. For instance: + + service Foo { + rpc Bar(google.protobuf.Empty) returns + (google.protobuf.Empty); + + } + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, service.DeleteDvrSessionRequest): + request = service.DeleteDvrSessionRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.delete_dvr_session + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + empty_pb2.Empty, + metadata_type=service.OperationMetadata, + ) + + # Done; return the response. + return response + + async def update_dvr_session( + self, + request: Optional[Union[service.UpdateDvrSessionRequest, dict]] = None, + *, + dvr_session: Optional[resources.DvrSession] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation_async.AsyncOperation: + r"""Updates the specified DVR session. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud.video import live_stream_v1 + + async def sample_update_dvr_session(): + # Create a client + client = live_stream_v1.LivestreamServiceAsyncClient() + + # Initialize request argument(s) + dvr_session = live_stream_v1.DvrSession() + dvr_session.dvr_manifests.manifest_key = "manifest_key_value" + + request = live_stream_v1.UpdateDvrSessionRequest( + dvr_session=dvr_session, + ) + + # Make the request + operation = client.update_dvr_session(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.video.live_stream_v1.types.UpdateDvrSessionRequest, dict]]): + The request object. Request message for + "LivestreamService.UpdateDvrSession". + dvr_session (:class:`google.cloud.video.live_stream_v1.types.DvrSession`): + Required. The DVR session resource to + be updated. + + This corresponds to the ``dvr_session`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + Required. Field mask is used to specify the fields to be + overwritten in the DvrSession resource by the update. + You can only update the following fields: + + - ``dvrWindows`` + + The fields specified in the update_mask are relative to + the resource, not the full request. A field will be + overwritten if it is in the mask. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.video.live_stream_v1.types.DvrSession` DvrSession is a sub-resource under channel. Each DvrSession represents a DVR + recording of the live stream for a specific time + range. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [dvr_session, 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, service.UpdateDvrSessionRequest): + request = service.UpdateDvrSessionRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if dvr_session is not None: + request.dvr_session = dvr_session + 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_dvr_session + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("dvr_session.name", request.dvr_session.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, + resources.DvrSession, + metadata_type=service.OperationMetadata, + ) + + # Done; return the response. + return response + async def create_asset( self, request: Optional[Union[service.CreateAssetRequest, dict]] = None, diff --git a/packages/google-cloud-video-live-stream/google/cloud/video/live_stream_v1/services/livestream_service/client.py b/packages/google-cloud-video-live-stream/google/cloud/video/live_stream_v1/services/livestream_service/client.py index 4359636eadd6..9444a03ade55 100644 --- a/packages/google-cloud-video-live-stream/google/cloud/video/live_stream_v1/services/livestream_service/client.py +++ b/packages/google-cloud-video-live-stream/google/cloud/video/live_stream_v1/services/livestream_service/client.py @@ -279,6 +279,30 @@ def parse_clip_path(path: str) -> Dict[str, str]: ) return m.groupdict() if m else {} + @staticmethod + def dvr_session_path( + project: str, + location: str, + channel: str, + dvr_session: str, + ) -> str: + """Returns a fully-qualified dvr_session string.""" + return "projects/{project}/locations/{location}/channels/{channel}/dvrSessions/{dvr_session}".format( + project=project, + location=location, + channel=channel, + dvr_session=dvr_session, + ) + + @staticmethod + def parse_dvr_session_path(path: str) -> Dict[str, str]: + """Parses a dvr_session path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/channels/(?P.+?)/dvrSessions/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + @staticmethod def event_path( project: str, @@ -2382,6 +2406,7 @@ def sample_update_input(): overwritten in the Input resource by the update. You can only update the following fields: + - ```tier`` `__ - ```preprocessingConfig`` `__ - ```securityRules`` `__ @@ -3336,7 +3361,7 @@ def delete_clip( ) -> operation.Operation: r"""Deletes the specified clip job resource. This method only deletes the clip job and does not delete the VOD - clip stored in the GCS. + clip stored in Cloud Storage. .. code-block:: python @@ -3457,6 +3482,669 @@ def sample_delete_clip(): # Done; return the response. return response + def create_dvr_session( + self, + request: Optional[Union[service.CreateDvrSessionRequest, dict]] = None, + *, + parent: Optional[str] = None, + dvr_session: Optional[resources.DvrSession] = None, + dvr_session_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: + r"""Creates a DVR session with the provided unique ID in + the specified channel. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud.video import live_stream_v1 + + def sample_create_dvr_session(): + # Create a client + client = live_stream_v1.LivestreamServiceClient() + + # Initialize request argument(s) + dvr_session = live_stream_v1.DvrSession() + dvr_session.dvr_manifests.manifest_key = "manifest_key_value" + + request = live_stream_v1.CreateDvrSessionRequest( + parent="parent_value", + dvr_session_id="dvr_session_id_value", + dvr_session=dvr_session, + ) + + # Make the request + operation = client.create_dvr_session(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.video.live_stream_v1.types.CreateDvrSessionRequest, dict]): + The request object. Request message for + "LivestreamService.CreateDvrSession". + parent (str): + Required. The parent resource name, in the following + form: + ``projects/{project}/locations/{location}/channels/{channelId}``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + dvr_session (google.cloud.video.live_stream_v1.types.DvrSession): + Required. The resource being created + This corresponds to the ``dvr_session`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + dvr_session_id (str): + Required. Id of the requesting object + in the following form: + + 1. 1 character minimum, 63 characters + maximum + 2. Only contains letters, digits, + underscores, and hyphens + + This corresponds to the ``dvr_session_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.video.live_stream_v1.types.DvrSession` DvrSession is a sub-resource under channel. Each DvrSession represents a DVR + recording of the live stream for a specific time + range. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent, dvr_session, dvr_session_id] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, service.CreateDvrSessionRequest): + request = service.CreateDvrSessionRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if dvr_session is not None: + request.dvr_session = dvr_session + if dvr_session_id is not None: + request.dvr_session_id = dvr_session_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_dvr_session] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + resources.DvrSession, + metadata_type=service.OperationMetadata, + ) + + # Done; return the response. + return response + + def list_dvr_sessions( + self, + request: Optional[Union[service.ListDvrSessionsRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListDvrSessionsPager: + r"""Returns a list of all DVR sessions in the specified + channel. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud.video import live_stream_v1 + + def sample_list_dvr_sessions(): + # Create a client + client = live_stream_v1.LivestreamServiceClient() + + # Initialize request argument(s) + request = live_stream_v1.ListDvrSessionsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_dvr_sessions(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.video.live_stream_v1.types.ListDvrSessionsRequest, dict]): + The request object. Request message for + "LivestreamService.ListDvrSessions". + parent (str): + Required. Parent value for + ListDvrSessionsRequest + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.video.live_stream_v1.services.livestream_service.pagers.ListDvrSessionsPager: + Response message for + "LivestreamService.ListDvrSessions". + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, service.ListDvrSessionsRequest): + request = service.ListDvrSessionsRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_dvr_sessions] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListDvrSessionsPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_dvr_session( + self, + request: Optional[Union[service.GetDvrSessionRequest, 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]]] = (), + ) -> resources.DvrSession: + r"""Returns the specified DVR session. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud.video import live_stream_v1 + + def sample_get_dvr_session(): + # Create a client + client = live_stream_v1.LivestreamServiceClient() + + # Initialize request argument(s) + request = live_stream_v1.GetDvrSessionRequest( + name="name_value", + ) + + # Make the request + response = client.get_dvr_session(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.video.live_stream_v1.types.GetDvrSessionRequest, dict]): + The request object. Request message for + "LivestreamService.GetDvrSession". + name (str): + Required. Name of the resource, in the following form: + ``projects/{project}/locations/{location}/channels/{channelId}/dvrSessions/{dvrSessionId}``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.video.live_stream_v1.types.DvrSession: + DvrSession is a sub-resource under + channel. Each DvrSession represents a + DVR recording of the live stream for a + specific time range. + + """ + # Create or coerce a protobuf request 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, service.GetDvrSessionRequest): + request = service.GetDvrSessionRequest(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_dvr_session] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def delete_dvr_session( + self, + request: Optional[Union[service.DeleteDvrSessionRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: + r"""Deletes the specified DVR session. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud.video import live_stream_v1 + + def sample_delete_dvr_session(): + # Create a client + client = live_stream_v1.LivestreamServiceClient() + + # Initialize request argument(s) + request = live_stream_v1.DeleteDvrSessionRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_dvr_session(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.video.live_stream_v1.types.DeleteDvrSessionRequest, dict]): + The request object. Request message for + "LivestreamService.DeleteDvrSession". + name (str): + Required. The name of the event resource, in the form + of: + ``projects/{project}/locations/{location}/channels/{channelId}/dvrSessions/{dvrSessionId}``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated + empty messages in your APIs. A typical example is to + use it as the request or the response type of an API + method. For instance: + + service Foo { + rpc Bar(google.protobuf.Empty) returns + (google.protobuf.Empty); + + } + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, service.DeleteDvrSessionRequest): + request = service.DeleteDvrSessionRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.delete_dvr_session] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + empty_pb2.Empty, + metadata_type=service.OperationMetadata, + ) + + # Done; return the response. + return response + + def update_dvr_session( + self, + request: Optional[Union[service.UpdateDvrSessionRequest, dict]] = None, + *, + dvr_session: Optional[resources.DvrSession] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: + r"""Updates the specified DVR session. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud.video import live_stream_v1 + + def sample_update_dvr_session(): + # Create a client + client = live_stream_v1.LivestreamServiceClient() + + # Initialize request argument(s) + dvr_session = live_stream_v1.DvrSession() + dvr_session.dvr_manifests.manifest_key = "manifest_key_value" + + request = live_stream_v1.UpdateDvrSessionRequest( + dvr_session=dvr_session, + ) + + # Make the request + operation = client.update_dvr_session(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.video.live_stream_v1.types.UpdateDvrSessionRequest, dict]): + The request object. Request message for + "LivestreamService.UpdateDvrSession". + dvr_session (google.cloud.video.live_stream_v1.types.DvrSession): + Required. The DVR session resource to + be updated. + + This corresponds to the ``dvr_session`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. Field mask is used to specify the fields to be + overwritten in the DvrSession resource by the update. + You can only update the following fields: + + - ``dvrWindows`` + + The fields specified in the update_mask are relative to + the resource, not the full request. A field will be + overwritten if it is in the mask. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.video.live_stream_v1.types.DvrSession` DvrSession is a sub-resource under channel. Each DvrSession represents a DVR + recording of the live stream for a specific time + range. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [dvr_session, 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, service.UpdateDvrSessionRequest): + request = service.UpdateDvrSessionRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if dvr_session is not None: + request.dvr_session = dvr_session + 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_dvr_session] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("dvr_session.name", request.dvr_session.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, + resources.DvrSession, + metadata_type=service.OperationMetadata, + ) + + # Done; return the response. + return response + def create_asset( self, request: Optional[Union[service.CreateAssetRequest, dict]] = None, diff --git a/packages/google-cloud-video-live-stream/google/cloud/video/live_stream_v1/services/livestream_service/pagers.py b/packages/google-cloud-video-live-stream/google/cloud/video/live_stream_v1/services/livestream_service/pagers.py index c23a58cdf89b..8742dc236dc6 100644 --- a/packages/google-cloud-video-live-stream/google/cloud/video/live_stream_v1/services/livestream_service/pagers.py +++ b/packages/google-cloud-video-live-stream/google/cloud/video/live_stream_v1/services/livestream_service/pagers.py @@ -665,6 +665,162 @@ def __repr__(self) -> str: return "{0}<{1!r}>".format(self.__class__.__name__, self._response) +class ListDvrSessionsPager: + """A pager for iterating through ``list_dvr_sessions`` requests. + + This class thinly wraps an initial + :class:`google.cloud.video.live_stream_v1.types.ListDvrSessionsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``dvr_sessions`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListDvrSessions`` requests and continue to iterate + through the ``dvr_sessions`` field on the + corresponding responses. + + All the usual :class:`google.cloud.video.live_stream_v1.types.ListDvrSessionsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[..., service.ListDvrSessionsResponse], + request: service.ListDvrSessionsRequest, + response: service.ListDvrSessionsResponse, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = () + ): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.video.live_stream_v1.types.ListDvrSessionsRequest): + The initial request object. + response (google.cloud.video.live_stream_v1.types.ListDvrSessionsResponse): + The initial response object. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + self._method = method + self._request = service.ListDvrSessionsRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[service.ListDvrSessionsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method( + self._request, + retry=self._retry, + timeout=self._timeout, + metadata=self._metadata, + ) + yield self._response + + def __iter__(self) -> Iterator[resources.DvrSession]: + for page in self.pages: + yield from page.dvr_sessions + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListDvrSessionsAsyncPager: + """A pager for iterating through ``list_dvr_sessions`` requests. + + This class thinly wraps an initial + :class:`google.cloud.video.live_stream_v1.types.ListDvrSessionsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``dvr_sessions`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListDvrSessions`` requests and continue to iterate + through the ``dvr_sessions`` field on the + corresponding responses. + + All the usual :class:`google.cloud.video.live_stream_v1.types.ListDvrSessionsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[..., Awaitable[service.ListDvrSessionsResponse]], + request: service.ListDvrSessionsRequest, + response: service.ListDvrSessionsResponse, + *, + retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = () + ): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.video.live_stream_v1.types.ListDvrSessionsRequest): + The initial request object. + response (google.cloud.video.live_stream_v1.types.ListDvrSessionsResponse): + The initial response object. + retry (google.api_core.retry.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + self._method = method + self._request = service.ListDvrSessionsRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[service.ListDvrSessionsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method( + self._request, + retry=self._retry, + timeout=self._timeout, + metadata=self._metadata, + ) + yield self._response + + def __aiter__(self) -> AsyncIterator[resources.DvrSession]: + async def async_generator(): + async for page in self.pages: + for response in page.dvr_sessions: + yield response + + return async_generator() + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + class ListAssetsPager: """A pager for iterating through ``list_assets`` requests. diff --git a/packages/google-cloud-video-live-stream/google/cloud/video/live_stream_v1/services/livestream_service/transports/base.py b/packages/google-cloud-video-live-stream/google/cloud/video/live_stream_v1/services/livestream_service/transports/base.py index 648f768d6ddf..8bc296610394 100644 --- a/packages/google-cloud-video-live-stream/google/cloud/video/live_stream_v1/services/livestream_service/transports/base.py +++ b/packages/google-cloud-video-live-stream/google/cloud/video/live_stream_v1/services/livestream_service/transports/base.py @@ -271,12 +271,30 @@ def _prep_wrapped_messages(self, client_info): ), self.list_clips: gapic_v1.method.wrap_method( self.list_clips, - default_timeout=None, + default_retry=retries.Retry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, client_info=client_info, ), self.get_clip: gapic_v1.method.wrap_method( self.get_clip, - default_timeout=None, + default_retry=retries.Retry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, client_info=client_info, ), self.create_clip: gapic_v1.method.wrap_method( @@ -289,6 +307,31 @@ def _prep_wrapped_messages(self, client_info): default_timeout=None, client_info=client_info, ), + self.create_dvr_session: gapic_v1.method.wrap_method( + self.create_dvr_session, + default_timeout=None, + client_info=client_info, + ), + self.list_dvr_sessions: gapic_v1.method.wrap_method( + self.list_dvr_sessions, + default_timeout=None, + client_info=client_info, + ), + self.get_dvr_session: gapic_v1.method.wrap_method( + self.get_dvr_session, + default_timeout=None, + client_info=client_info, + ), + self.delete_dvr_session: gapic_v1.method.wrap_method( + self.delete_dvr_session, + default_timeout=None, + client_info=client_info, + ), + self.update_dvr_session: gapic_v1.method.wrap_method( + self.update_dvr_session, + default_timeout=None, + client_info=client_info, + ), self.create_asset: gapic_v1.method.wrap_method( self.create_asset, default_timeout=None, @@ -301,17 +344,44 @@ def _prep_wrapped_messages(self, client_info): ), self.get_asset: gapic_v1.method.wrap_method( self.get_asset, - default_timeout=None, + default_retry=retries.Retry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, client_info=client_info, ), self.list_assets: gapic_v1.method.wrap_method( self.list_assets, - default_timeout=None, + default_retry=retries.Retry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, client_info=client_info, ), self.get_pool: gapic_v1.method.wrap_method( self.get_pool, - default_timeout=None, + default_retry=retries.Retry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, client_info=client_info, ), self.update_pool: gapic_v1.method.wrap_method( @@ -540,6 +610,53 @@ def delete_clip( ]: raise NotImplementedError() + @property + def create_dvr_session( + self, + ) -> Callable[ + [service.CreateDvrSessionRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + + @property + def list_dvr_sessions( + self, + ) -> Callable[ + [service.ListDvrSessionsRequest], + Union[ + service.ListDvrSessionsResponse, Awaitable[service.ListDvrSessionsResponse] + ], + ]: + raise NotImplementedError() + + @property + def get_dvr_session( + self, + ) -> Callable[ + [service.GetDvrSessionRequest], + Union[resources.DvrSession, Awaitable[resources.DvrSession]], + ]: + raise NotImplementedError() + + @property + def delete_dvr_session( + self, + ) -> Callable[ + [service.DeleteDvrSessionRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + + @property + def update_dvr_session( + self, + ) -> Callable[ + [service.UpdateDvrSessionRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + @property def create_asset( self, diff --git a/packages/google-cloud-video-live-stream/google/cloud/video/live_stream_v1/services/livestream_service/transports/grpc.py b/packages/google-cloud-video-live-stream/google/cloud/video/live_stream_v1/services/livestream_service/transports/grpc.py index 1c42aa002a71..40587679f184 100644 --- a/packages/google-cloud-video-live-stream/google/cloud/video/live_stream_v1/services/livestream_service/transports/grpc.py +++ b/packages/google-cloud-video-live-stream/google/cloud/video/live_stream_v1/services/livestream_service/transports/grpc.py @@ -844,7 +844,7 @@ def delete_clip( Deletes the specified clip job resource. This method only deletes the clip job and does not delete the VOD - clip stored in the GCS. + clip stored in Cloud Storage. Returns: Callable[[~.DeleteClipRequest], @@ -864,6 +864,138 @@ def delete_clip( ) return self._stubs["delete_clip"] + @property + def create_dvr_session( + self, + ) -> Callable[[service.CreateDvrSessionRequest], operations_pb2.Operation]: + r"""Return a callable for the create dvr session method over gRPC. + + Creates a DVR session with the provided unique ID in + the specified channel. + + Returns: + Callable[[~.CreateDvrSessionRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "create_dvr_session" not in self._stubs: + self._stubs["create_dvr_session"] = self._logged_channel.unary_unary( + "/google.cloud.video.livestream.v1.LivestreamService/CreateDvrSession", + request_serializer=service.CreateDvrSessionRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["create_dvr_session"] + + @property + def list_dvr_sessions( + self, + ) -> Callable[[service.ListDvrSessionsRequest], service.ListDvrSessionsResponse]: + r"""Return a callable for the list dvr sessions method over gRPC. + + Returns a list of all DVR sessions in the specified + channel. + + Returns: + Callable[[~.ListDvrSessionsRequest], + ~.ListDvrSessionsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_dvr_sessions" not in self._stubs: + self._stubs["list_dvr_sessions"] = self._logged_channel.unary_unary( + "/google.cloud.video.livestream.v1.LivestreamService/ListDvrSessions", + request_serializer=service.ListDvrSessionsRequest.serialize, + response_deserializer=service.ListDvrSessionsResponse.deserialize, + ) + return self._stubs["list_dvr_sessions"] + + @property + def get_dvr_session( + self, + ) -> Callable[[service.GetDvrSessionRequest], resources.DvrSession]: + r"""Return a callable for the get dvr session method over gRPC. + + Returns the specified DVR session. + + Returns: + Callable[[~.GetDvrSessionRequest], + ~.DvrSession]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_dvr_session" not in self._stubs: + self._stubs["get_dvr_session"] = self._logged_channel.unary_unary( + "/google.cloud.video.livestream.v1.LivestreamService/GetDvrSession", + request_serializer=service.GetDvrSessionRequest.serialize, + response_deserializer=resources.DvrSession.deserialize, + ) + return self._stubs["get_dvr_session"] + + @property + def delete_dvr_session( + self, + ) -> Callable[[service.DeleteDvrSessionRequest], operations_pb2.Operation]: + r"""Return a callable for the delete dvr session method over gRPC. + + Deletes the specified DVR session. + + Returns: + Callable[[~.DeleteDvrSessionRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_dvr_session" not in self._stubs: + self._stubs["delete_dvr_session"] = self._logged_channel.unary_unary( + "/google.cloud.video.livestream.v1.LivestreamService/DeleteDvrSession", + request_serializer=service.DeleteDvrSessionRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["delete_dvr_session"] + + @property + def update_dvr_session( + self, + ) -> Callable[[service.UpdateDvrSessionRequest], operations_pb2.Operation]: + r"""Return a callable for the update dvr session method over gRPC. + + Updates the specified DVR session. + + Returns: + Callable[[~.UpdateDvrSessionRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "update_dvr_session" not in self._stubs: + self._stubs["update_dvr_session"] = self._logged_channel.unary_unary( + "/google.cloud.video.livestream.v1.LivestreamService/UpdateDvrSession", + request_serializer=service.UpdateDvrSessionRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["update_dvr_session"] + @property def create_asset( self, diff --git a/packages/google-cloud-video-live-stream/google/cloud/video/live_stream_v1/services/livestream_service/transports/grpc_asyncio.py b/packages/google-cloud-video-live-stream/google/cloud/video/live_stream_v1/services/livestream_service/transports/grpc_asyncio.py index 70be035b3af5..de70f0752978 100644 --- a/packages/google-cloud-video-live-stream/google/cloud/video/live_stream_v1/services/livestream_service/transports/grpc_asyncio.py +++ b/packages/google-cloud-video-live-stream/google/cloud/video/live_stream_v1/services/livestream_service/transports/grpc_asyncio.py @@ -864,7 +864,7 @@ def delete_clip( Deletes the specified clip job resource. This method only deletes the clip job and does not delete the VOD - clip stored in the GCS. + clip stored in Cloud Storage. Returns: Callable[[~.DeleteClipRequest], @@ -884,6 +884,146 @@ def delete_clip( ) return self._stubs["delete_clip"] + @property + def create_dvr_session( + self, + ) -> Callable[ + [service.CreateDvrSessionRequest], Awaitable[operations_pb2.Operation] + ]: + r"""Return a callable for the create dvr session method over gRPC. + + Creates a DVR session with the provided unique ID in + the specified channel. + + Returns: + Callable[[~.CreateDvrSessionRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "create_dvr_session" not in self._stubs: + self._stubs["create_dvr_session"] = self._logged_channel.unary_unary( + "/google.cloud.video.livestream.v1.LivestreamService/CreateDvrSession", + request_serializer=service.CreateDvrSessionRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["create_dvr_session"] + + @property + def list_dvr_sessions( + self, + ) -> Callable[ + [service.ListDvrSessionsRequest], Awaitable[service.ListDvrSessionsResponse] + ]: + r"""Return a callable for the list dvr sessions method over gRPC. + + Returns a list of all DVR sessions in the specified + channel. + + Returns: + Callable[[~.ListDvrSessionsRequest], + Awaitable[~.ListDvrSessionsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_dvr_sessions" not in self._stubs: + self._stubs["list_dvr_sessions"] = self._logged_channel.unary_unary( + "/google.cloud.video.livestream.v1.LivestreamService/ListDvrSessions", + request_serializer=service.ListDvrSessionsRequest.serialize, + response_deserializer=service.ListDvrSessionsResponse.deserialize, + ) + return self._stubs["list_dvr_sessions"] + + @property + def get_dvr_session( + self, + ) -> Callable[[service.GetDvrSessionRequest], Awaitable[resources.DvrSession]]: + r"""Return a callable for the get dvr session method over gRPC. + + Returns the specified DVR session. + + Returns: + Callable[[~.GetDvrSessionRequest], + Awaitable[~.DvrSession]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_dvr_session" not in self._stubs: + self._stubs["get_dvr_session"] = self._logged_channel.unary_unary( + "/google.cloud.video.livestream.v1.LivestreamService/GetDvrSession", + request_serializer=service.GetDvrSessionRequest.serialize, + response_deserializer=resources.DvrSession.deserialize, + ) + return self._stubs["get_dvr_session"] + + @property + def delete_dvr_session( + self, + ) -> Callable[ + [service.DeleteDvrSessionRequest], Awaitable[operations_pb2.Operation] + ]: + r"""Return a callable for the delete dvr session method over gRPC. + + Deletes the specified DVR session. + + Returns: + Callable[[~.DeleteDvrSessionRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_dvr_session" not in self._stubs: + self._stubs["delete_dvr_session"] = self._logged_channel.unary_unary( + "/google.cloud.video.livestream.v1.LivestreamService/DeleteDvrSession", + request_serializer=service.DeleteDvrSessionRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["delete_dvr_session"] + + @property + def update_dvr_session( + self, + ) -> Callable[ + [service.UpdateDvrSessionRequest], Awaitable[operations_pb2.Operation] + ]: + r"""Return a callable for the update dvr session method over gRPC. + + Updates the specified DVR session. + + Returns: + Callable[[~.UpdateDvrSessionRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "update_dvr_session" not in self._stubs: + self._stubs["update_dvr_session"] = self._logged_channel.unary_unary( + "/google.cloud.video.livestream.v1.LivestreamService/UpdateDvrSession", + request_serializer=service.UpdateDvrSessionRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["update_dvr_session"] + @property def create_asset( self, @@ -1178,12 +1318,30 @@ def _prep_wrapped_messages(self, client_info): ), self.list_clips: self._wrap_method( self.list_clips, - default_timeout=None, + default_retry=retries.AsyncRetry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, client_info=client_info, ), self.get_clip: self._wrap_method( self.get_clip, - default_timeout=None, + default_retry=retries.AsyncRetry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, client_info=client_info, ), self.create_clip: self._wrap_method( @@ -1196,6 +1354,31 @@ def _prep_wrapped_messages(self, client_info): default_timeout=None, client_info=client_info, ), + self.create_dvr_session: self._wrap_method( + self.create_dvr_session, + default_timeout=None, + client_info=client_info, + ), + self.list_dvr_sessions: self._wrap_method( + self.list_dvr_sessions, + default_timeout=None, + client_info=client_info, + ), + self.get_dvr_session: self._wrap_method( + self.get_dvr_session, + default_timeout=None, + client_info=client_info, + ), + self.delete_dvr_session: self._wrap_method( + self.delete_dvr_session, + default_timeout=None, + client_info=client_info, + ), + self.update_dvr_session: self._wrap_method( + self.update_dvr_session, + default_timeout=None, + client_info=client_info, + ), self.create_asset: self._wrap_method( self.create_asset, default_timeout=None, @@ -1208,17 +1391,44 @@ def _prep_wrapped_messages(self, client_info): ), self.get_asset: self._wrap_method( self.get_asset, - default_timeout=None, + default_retry=retries.AsyncRetry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, client_info=client_info, ), self.list_assets: self._wrap_method( self.list_assets, - default_timeout=None, + default_retry=retries.AsyncRetry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, client_info=client_info, ), self.get_pool: self._wrap_method( self.get_pool, - default_timeout=None, + default_retry=retries.AsyncRetry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, client_info=client_info, ), self.update_pool: self._wrap_method( diff --git a/packages/google-cloud-video-live-stream/google/cloud/video/live_stream_v1/services/livestream_service/transports/rest.py b/packages/google-cloud-video-live-stream/google/cloud/video/live_stream_v1/services/livestream_service/transports/rest.py index 9fe51e4d5dc3..1355d49fa914 100644 --- a/packages/google-cloud-video-live-stream/google/cloud/video/live_stream_v1/services/livestream_service/transports/rest.py +++ b/packages/google-cloud-video-live-stream/google/cloud/video/live_stream_v1/services/livestream_service/transports/rest.py @@ -99,6 +99,14 @@ def post_create_clip(self, response): logging.log(f"Received response: {response}") return response + def pre_create_dvr_session(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_dvr_session(self, response): + logging.log(f"Received response: {response}") + return response + def pre_create_event(self, request, metadata): logging.log(f"Received request: {request}") return request, metadata @@ -139,6 +147,14 @@ def post_delete_clip(self, response): logging.log(f"Received response: {response}") return response + def pre_delete_dvr_session(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_delete_dvr_session(self, response): + logging.log(f"Received response: {response}") + return response + def pre_delete_event(self, request, metadata): logging.log(f"Received request: {request}") return request, metadata @@ -175,6 +191,14 @@ def post_get_clip(self, response): logging.log(f"Received response: {response}") return response + def pre_get_dvr_session(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_dvr_session(self, response): + logging.log(f"Received response: {response}") + return response + def pre_get_event(self, request, metadata): logging.log(f"Received request: {request}") return request, metadata @@ -223,6 +247,14 @@ def post_list_clips(self, response): logging.log(f"Received response: {response}") return response + def pre_list_dvr_sessions(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_dvr_sessions(self, response): + logging.log(f"Received response: {response}") + return response + def pre_list_events(self, request, metadata): logging.log(f"Received request: {request}") return request, metadata @@ -263,6 +295,14 @@ def post_update_channel(self, response): logging.log(f"Received response: {response}") return response + def pre_update_dvr_session(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_dvr_session(self, response): + logging.log(f"Received response: {response}") + return response + def pre_update_input(self, request, metadata): logging.log(f"Received request: {request}") return request, metadata @@ -423,6 +463,54 @@ def post_create_clip_with_metadata( """ return response, metadata + def pre_create_dvr_session( + self, + request: service.CreateDvrSessionRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + service.CreateDvrSessionRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for create_dvr_session + + Override in a subclass to manipulate the request or metadata + before they are sent to the LivestreamService server. + """ + return request, metadata + + def post_create_dvr_session( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for create_dvr_session + + DEPRECATED. Please use the `post_create_dvr_session_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the LivestreamService server but before + it is returned to user code. This `post_create_dvr_session` interceptor runs + before the `post_create_dvr_session_with_metadata` interceptor. + """ + return response + + def post_create_dvr_session_with_metadata( + self, + response: operations_pb2.Operation, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for create_dvr_session + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the LivestreamService server but before it is returned to user code. + + We recommend only using this `post_create_dvr_session_with_metadata` + interceptor in new development instead of the `post_create_dvr_session` interceptor. + When both interceptors are used, this `post_create_dvr_session_with_metadata` interceptor runs after the + `post_create_dvr_session` interceptor. The (possibly modified) response returned by + `post_create_dvr_session` will be passed to + `post_create_dvr_session_with_metadata`. + """ + return response, metadata + def pre_create_event( self, request: service.CreateEventRequest, @@ -651,6 +739,54 @@ def post_delete_clip_with_metadata( """ return response, metadata + def pre_delete_dvr_session( + self, + request: service.DeleteDvrSessionRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + service.DeleteDvrSessionRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for delete_dvr_session + + Override in a subclass to manipulate the request or metadata + before they are sent to the LivestreamService server. + """ + return request, metadata + + def post_delete_dvr_session( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for delete_dvr_session + + DEPRECATED. Please use the `post_delete_dvr_session_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the LivestreamService server but before + it is returned to user code. This `post_delete_dvr_session` interceptor runs + before the `post_delete_dvr_session_with_metadata` interceptor. + """ + return response + + def post_delete_dvr_session_with_metadata( + self, + response: operations_pb2.Operation, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for delete_dvr_session + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the LivestreamService server but before it is returned to user code. + + We recommend only using this `post_delete_dvr_session_with_metadata` + interceptor in new development instead of the `post_delete_dvr_session` interceptor. + When both interceptors are used, this `post_delete_dvr_session_with_metadata` interceptor runs after the + `post_delete_dvr_session` interceptor. The (possibly modified) response returned by + `post_delete_dvr_session` will be passed to + `post_delete_dvr_session_with_metadata`. + """ + return response, metadata + def pre_delete_event( self, request: service.DeleteEventRequest, @@ -841,6 +977,52 @@ def post_get_clip_with_metadata( """ return response, metadata + def pre_get_dvr_session( + self, + request: service.GetDvrSessionRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[service.GetDvrSessionRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for get_dvr_session + + Override in a subclass to manipulate the request or metadata + before they are sent to the LivestreamService server. + """ + return request, metadata + + def post_get_dvr_session( + self, response: resources.DvrSession + ) -> resources.DvrSession: + """Post-rpc interceptor for get_dvr_session + + DEPRECATED. Please use the `post_get_dvr_session_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the LivestreamService server but before + it is returned to user code. This `post_get_dvr_session` interceptor runs + before the `post_get_dvr_session_with_metadata` interceptor. + """ + return response + + def post_get_dvr_session_with_metadata( + self, + response: resources.DvrSession, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[resources.DvrSession, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for get_dvr_session + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the LivestreamService server but before it is returned to user code. + + We recommend only using this `post_get_dvr_session_with_metadata` + interceptor in new development instead of the `post_get_dvr_session` interceptor. + When both interceptors are used, this `post_get_dvr_session_with_metadata` interceptor runs after the + `post_get_dvr_session` interceptor. The (possibly modified) response returned by + `post_get_dvr_session` will be passed to + `post_get_dvr_session_with_metadata`. + """ + return response, metadata + def pre_get_event( self, request: service.GetEventRequest, @@ -1111,6 +1293,54 @@ def post_list_clips_with_metadata( """ return response, metadata + def pre_list_dvr_sessions( + self, + request: service.ListDvrSessionsRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[service.ListDvrSessionsRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for list_dvr_sessions + + Override in a subclass to manipulate the request or metadata + before they are sent to the LivestreamService server. + """ + return request, metadata + + def post_list_dvr_sessions( + self, response: service.ListDvrSessionsResponse + ) -> service.ListDvrSessionsResponse: + """Post-rpc interceptor for list_dvr_sessions + + DEPRECATED. Please use the `post_list_dvr_sessions_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the LivestreamService server but before + it is returned to user code. This `post_list_dvr_sessions` interceptor runs + before the `post_list_dvr_sessions_with_metadata` interceptor. + """ + return response + + def post_list_dvr_sessions_with_metadata( + self, + response: service.ListDvrSessionsResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + service.ListDvrSessionsResponse, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Post-rpc interceptor for list_dvr_sessions + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the LivestreamService server but before it is returned to user code. + + We recommend only using this `post_list_dvr_sessions_with_metadata` + interceptor in new development instead of the `post_list_dvr_sessions` interceptor. + When both interceptors are used, this `post_list_dvr_sessions_with_metadata` interceptor runs after the + `post_list_dvr_sessions` interceptor. The (possibly modified) response returned by + `post_list_dvr_sessions` will be passed to + `post_list_dvr_sessions_with_metadata`. + """ + return response, metadata + def pre_list_events( self, request: service.ListEventsRequest, @@ -1341,6 +1571,54 @@ def post_update_channel_with_metadata( """ return response, metadata + def pre_update_dvr_session( + self, + request: service.UpdateDvrSessionRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + service.UpdateDvrSessionRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for update_dvr_session + + Override in a subclass to manipulate the request or metadata + before they are sent to the LivestreamService server. + """ + return request, metadata + + def post_update_dvr_session( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for update_dvr_session + + DEPRECATED. Please use the `post_update_dvr_session_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the LivestreamService server but before + it is returned to user code. This `post_update_dvr_session` interceptor runs + before the `post_update_dvr_session_with_metadata` interceptor. + """ + return response + + def post_update_dvr_session_with_metadata( + self, + response: operations_pb2.Operation, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for update_dvr_session + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the LivestreamService server but before it is returned to user code. + + We recommend only using this `post_update_dvr_session_with_metadata` + interceptor in new development instead of the `post_update_dvr_session` interceptor. + When both interceptors are used, this `post_update_dvr_session_with_metadata` interceptor runs after the + `post_update_dvr_session` interceptor. The (possibly modified) response returned by + `post_update_dvr_session` will be passed to + `post_update_dvr_session_with_metadata`. + """ + return response, metadata + def pre_update_input( self, request: service.UpdateInputRequest, @@ -2182,11 +2460,12 @@ def __call__( ) return resp - class _CreateEvent( - _BaseLivestreamServiceRestTransport._BaseCreateEvent, LivestreamServiceRestStub + class _CreateDvrSession( + _BaseLivestreamServiceRestTransport._BaseCreateDvrSession, + LivestreamServiceRestStub, ): def __hash__(self): - return hash("LivestreamServiceRestTransport.CreateEvent") + return hash("LivestreamServiceRestTransport.CreateDvrSession") @staticmethod def _get_response( @@ -2213,18 +2492,18 @@ def _get_response( def __call__( self, - request: service.CreateEventRequest, + request: service.CreateDvrSessionRequest, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> resources.Event: - r"""Call the create event method over HTTP. + ) -> operations_pb2.Operation: + r"""Call the create dvr session method over HTTP. Args: - request (~.service.CreateEventRequest): + request (~.service.CreateDvrSessionRequest): The request object. Request message for - "LivestreamService.CreateEvent". + "LivestreamService.CreateDvrSession". retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -2234,29 +2513,30 @@ def __call__( be of type `bytes`. Returns: - ~.resources.Event: - Event is a sub-resource of a channel, - which can be scheduled by the user to - execute operations on a channel resource - without having to stop the channel. + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. """ http_options = ( - _BaseLivestreamServiceRestTransport._BaseCreateEvent._get_http_options() + _BaseLivestreamServiceRestTransport._BaseCreateDvrSession._get_http_options() ) - request, metadata = self._interceptor.pre_create_event(request, metadata) - transcoded_request = _BaseLivestreamServiceRestTransport._BaseCreateEvent._get_transcoded_request( + request, metadata = self._interceptor.pre_create_dvr_session( + request, metadata + ) + transcoded_request = _BaseLivestreamServiceRestTransport._BaseCreateDvrSession._get_transcoded_request( http_options, request ) - body = _BaseLivestreamServiceRestTransport._BaseCreateEvent._get_request_body_json( + body = _BaseLivestreamServiceRestTransport._BaseCreateDvrSession._get_request_body_json( transcoded_request ) # Jsonify the query params - query_params = _BaseLivestreamServiceRestTransport._BaseCreateEvent._get_query_params_json( + query_params = _BaseLivestreamServiceRestTransport._BaseCreateDvrSession._get_query_params_json( transcoded_request ) @@ -2268,7 +2548,7 @@ def __call__( ) method = transcoded_request["method"] try: - request_payload = type(request).to_json(request) + request_payload = json_format.MessageToJson(request) except: request_payload = None http_request = { @@ -2278,17 +2558,17 @@ def __call__( "headers": dict(metadata), } _LOGGER.debug( - f"Sending request for google.cloud.video.livestream_v1.LivestreamServiceClient.CreateEvent", + f"Sending request for google.cloud.video.livestream_v1.LivestreamServiceClient.CreateDvrSession", extra={ "serviceName": "google.cloud.video.livestream.v1.LivestreamService", - "rpcName": "CreateEvent", + "rpcName": "CreateDvrSession", "httpRequest": http_request, "metadata": http_request["headers"], }, ) # Send the request - response = LivestreamServiceRestTransport._CreateEvent._get_response( + response = LivestreamServiceRestTransport._CreateDvrSession._get_response( self._host, metadata, query_params, @@ -2304,21 +2584,19 @@ def __call__( raise core_exceptions.from_http_response(response) # Return the response - resp = resources.Event() - pb_resp = resources.Event.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) - resp = self._interceptor.post_create_event(resp) + resp = self._interceptor.post_create_dvr_session(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_create_event_with_metadata( + resp, _ = self._interceptor.post_create_dvr_session_with_metadata( resp, response_metadata ) if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( logging.DEBUG ): # pragma: NO COVER try: - response_payload = resources.Event.to_json(response) + response_payload = json_format.MessageToJson(resp) except: response_payload = None http_response = { @@ -2327,21 +2605,21 @@ def __call__( "status": response.status_code, } _LOGGER.debug( - "Received response for google.cloud.video.livestream_v1.LivestreamServiceClient.create_event", + "Received response for google.cloud.video.livestream_v1.LivestreamServiceClient.create_dvr_session", extra={ "serviceName": "google.cloud.video.livestream.v1.LivestreamService", - "rpcName": "CreateEvent", + "rpcName": "CreateDvrSession", "metadata": http_response["headers"], "httpResponse": http_response, }, ) return resp - class _CreateInput( - _BaseLivestreamServiceRestTransport._BaseCreateInput, LivestreamServiceRestStub + class _CreateEvent( + _BaseLivestreamServiceRestTransport._BaseCreateEvent, LivestreamServiceRestStub ): def __hash__(self): - return hash("LivestreamServiceRestTransport.CreateInput") + return hash("LivestreamServiceRestTransport.CreateEvent") @staticmethod def _get_response( @@ -2368,18 +2646,18 @@ def _get_response( def __call__( self, - request: service.CreateInputRequest, + request: service.CreateEventRequest, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operations_pb2.Operation: - r"""Call the create input method over HTTP. + ) -> resources.Event: + r"""Call the create event method over HTTP. Args: - request (~.service.CreateInputRequest): + request (~.service.CreateEventRequest): The request object. Request message for - "LivestreamService.CreateInput". + "LivestreamService.CreateEvent". retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -2389,28 +2667,29 @@ def __call__( be of type `bytes`. Returns: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. + ~.resources.Event: + Event is a sub-resource of a channel, + which can be scheduled by the user to + execute operations on a channel resource + without having to stop the channel. """ http_options = ( - _BaseLivestreamServiceRestTransport._BaseCreateInput._get_http_options() + _BaseLivestreamServiceRestTransport._BaseCreateEvent._get_http_options() ) - request, metadata = self._interceptor.pre_create_input(request, metadata) - transcoded_request = _BaseLivestreamServiceRestTransport._BaseCreateInput._get_transcoded_request( + request, metadata = self._interceptor.pre_create_event(request, metadata) + transcoded_request = _BaseLivestreamServiceRestTransport._BaseCreateEvent._get_transcoded_request( http_options, request ) - body = _BaseLivestreamServiceRestTransport._BaseCreateInput._get_request_body_json( + body = _BaseLivestreamServiceRestTransport._BaseCreateEvent._get_request_body_json( transcoded_request ) # Jsonify the query params - query_params = _BaseLivestreamServiceRestTransport._BaseCreateInput._get_query_params_json( + query_params = _BaseLivestreamServiceRestTransport._BaseCreateEvent._get_query_params_json( transcoded_request ) @@ -2422,7 +2701,7 @@ def __call__( ) method = transcoded_request["method"] try: - request_payload = json_format.MessageToJson(request) + request_payload = type(request).to_json(request) except: request_payload = None http_request = { @@ -2432,7 +2711,161 @@ def __call__( "headers": dict(metadata), } _LOGGER.debug( - f"Sending request for google.cloud.video.livestream_v1.LivestreamServiceClient.CreateInput", + f"Sending request for google.cloud.video.livestream_v1.LivestreamServiceClient.CreateEvent", + extra={ + "serviceName": "google.cloud.video.livestream.v1.LivestreamService", + "rpcName": "CreateEvent", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = LivestreamServiceRestTransport._CreateEvent._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = resources.Event() + pb_resp = resources.Event.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_create_event(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_create_event_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = resources.Event.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.video.livestream_v1.LivestreamServiceClient.create_event", + extra={ + "serviceName": "google.cloud.video.livestream.v1.LivestreamService", + "rpcName": "CreateEvent", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _CreateInput( + _BaseLivestreamServiceRestTransport._BaseCreateInput, LivestreamServiceRestStub + ): + def __hash__(self): + return hash("LivestreamServiceRestTransport.CreateInput") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: service.CreateInputRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + r"""Call the create input method over HTTP. + + Args: + request (~.service.CreateInputRequest): + The request object. Request message for + "LivestreamService.CreateInput". + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each 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 = ( + _BaseLivestreamServiceRestTransport._BaseCreateInput._get_http_options() + ) + + request, metadata = self._interceptor.pre_create_input(request, metadata) + transcoded_request = _BaseLivestreamServiceRestTransport._BaseCreateInput._get_transcoded_request( + http_options, request + ) + + body = _BaseLivestreamServiceRestTransport._BaseCreateInput._get_request_body_json( + transcoded_request + ) + + # Jsonify the query params + query_params = _BaseLivestreamServiceRestTransport._BaseCreateInput._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.video.livestream_v1.LivestreamServiceClient.CreateInput", extra={ "serviceName": "google.cloud.video.livestream.v1.LivestreamService", "rpcName": "CreateInput", @@ -2928,6 +3361,155 @@ def __call__( ) return resp + class _DeleteDvrSession( + _BaseLivestreamServiceRestTransport._BaseDeleteDvrSession, + LivestreamServiceRestStub, + ): + def __hash__(self): + return hash("LivestreamServiceRestTransport.DeleteDvrSession") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: service.DeleteDvrSessionRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + r"""Call the delete dvr session method over HTTP. + + Args: + request (~.service.DeleteDvrSessionRequest): + The request object. Request message for + "LivestreamService.DeleteDvrSession". + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each 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 = ( + _BaseLivestreamServiceRestTransport._BaseDeleteDvrSession._get_http_options() + ) + + request, metadata = self._interceptor.pre_delete_dvr_session( + request, metadata + ) + transcoded_request = _BaseLivestreamServiceRestTransport._BaseDeleteDvrSession._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = _BaseLivestreamServiceRestTransport._BaseDeleteDvrSession._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.video.livestream_v1.LivestreamServiceClient.DeleteDvrSession", + extra={ + "serviceName": "google.cloud.video.livestream.v1.LivestreamService", + "rpcName": "DeleteDvrSession", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = LivestreamServiceRestTransport._DeleteDvrSession._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_delete_dvr_session(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_delete_dvr_session_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.video.livestream_v1.LivestreamServiceClient.delete_dvr_session", + extra={ + "serviceName": "google.cloud.video.livestream.v1.LivestreamService", + "rpcName": "DeleteDvrSession", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + class _DeleteEvent( _BaseLivestreamServiceRestTransport._BaseDeleteEvent, LivestreamServiceRestStub ): @@ -3300,16 +3882,169 @@ def __call__( json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_get_asset(resp) + resp = self._interceptor.post_get_asset(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_get_asset_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = resources.Asset.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.video.livestream_v1.LivestreamServiceClient.get_asset", + extra={ + "serviceName": "google.cloud.video.livestream.v1.LivestreamService", + "rpcName": "GetAsset", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _GetChannel( + _BaseLivestreamServiceRestTransport._BaseGetChannel, LivestreamServiceRestStub + ): + def __hash__(self): + return hash("LivestreamServiceRestTransport.GetChannel") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: service.GetChannelRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> resources.Channel: + r"""Call the get channel method over HTTP. + + Args: + request (~.service.GetChannelRequest): + The request object. Request message for + "LivestreamService.GetChannel". + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.resources.Channel: + Channel resource represents the + processor that does a user-defined + "streaming" operation, which includes + getting an input stream through an + input, transcoding it to multiple + renditions, and publishing output live + streams in certain formats (for example, + HLS or DASH) to the specified location. + + """ + + http_options = ( + _BaseLivestreamServiceRestTransport._BaseGetChannel._get_http_options() + ) + + request, metadata = self._interceptor.pre_get_channel(request, metadata) + transcoded_request = _BaseLivestreamServiceRestTransport._BaseGetChannel._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = _BaseLivestreamServiceRestTransport._BaseGetChannel._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.video.livestream_v1.LivestreamServiceClient.GetChannel", + extra={ + "serviceName": "google.cloud.video.livestream.v1.LivestreamService", + "rpcName": "GetChannel", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = LivestreamServiceRestTransport._GetChannel._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 = resources.Channel() + pb_resp = resources.Channel.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_get_channel(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_get_asset_with_metadata( + resp, _ = self._interceptor.post_get_channel_with_metadata( resp, response_metadata ) if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( logging.DEBUG ): # pragma: NO COVER try: - response_payload = resources.Asset.to_json(response) + response_payload = resources.Channel.to_json(response) except: response_payload = None http_response = { @@ -3318,21 +4053,21 @@ def __call__( "status": response.status_code, } _LOGGER.debug( - "Received response for google.cloud.video.livestream_v1.LivestreamServiceClient.get_asset", + "Received response for google.cloud.video.livestream_v1.LivestreamServiceClient.get_channel", extra={ "serviceName": "google.cloud.video.livestream.v1.LivestreamService", - "rpcName": "GetAsset", + "rpcName": "GetChannel", "metadata": http_response["headers"], "httpResponse": http_response, }, ) return resp - class _GetChannel( - _BaseLivestreamServiceRestTransport._BaseGetChannel, LivestreamServiceRestStub + class _GetClip( + _BaseLivestreamServiceRestTransport._BaseGetClip, LivestreamServiceRestStub ): def __hash__(self): - return hash("LivestreamServiceRestTransport.GetChannel") + return hash("LivestreamServiceRestTransport.GetClip") @staticmethod def _get_response( @@ -3358,18 +4093,18 @@ def _get_response( def __call__( self, - request: service.GetChannelRequest, + request: service.GetClipRequest, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> resources.Channel: - r"""Call the get channel method over HTTP. + ) -> resources.Clip: + r"""Call the get clip method over HTTP. Args: - request (~.service.GetChannelRequest): + request (~.service.GetClipRequest): The request object. Request message for - "LivestreamService.GetChannel". + "LivestreamService.GetClip". retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -3379,30 +4114,29 @@ def __call__( be of type `bytes`. Returns: - ~.resources.Channel: - Channel resource represents the - processor that does a user-defined - "streaming" operation, which includes - getting an input stream through an - input, transcoding it to multiple - renditions, and publishing output live - streams in certain formats (for example, - HLS or DASH) to the specified location. + ~.resources.Clip: + Clip is a sub-resource under channel. + Each clip represents a clipping + operation that generates a VOD playlist + from its channel given a set of + timestamp ranges. """ http_options = ( - _BaseLivestreamServiceRestTransport._BaseGetChannel._get_http_options() + _BaseLivestreamServiceRestTransport._BaseGetClip._get_http_options() ) - request, metadata = self._interceptor.pre_get_channel(request, metadata) - transcoded_request = _BaseLivestreamServiceRestTransport._BaseGetChannel._get_transcoded_request( + request, metadata = self._interceptor.pre_get_clip(request, metadata) + transcoded_request = _BaseLivestreamServiceRestTransport._BaseGetClip._get_transcoded_request( http_options, request ) # Jsonify the query params - query_params = _BaseLivestreamServiceRestTransport._BaseGetChannel._get_query_params_json( - transcoded_request + query_params = ( + _BaseLivestreamServiceRestTransport._BaseGetClip._get_query_params_json( + transcoded_request + ) ) if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( @@ -3423,17 +4157,17 @@ def __call__( "headers": dict(metadata), } _LOGGER.debug( - f"Sending request for google.cloud.video.livestream_v1.LivestreamServiceClient.GetChannel", + f"Sending request for google.cloud.video.livestream_v1.LivestreamServiceClient.GetClip", extra={ "serviceName": "google.cloud.video.livestream.v1.LivestreamService", - "rpcName": "GetChannel", + "rpcName": "GetClip", "httpRequest": http_request, "metadata": http_request["headers"], }, ) # Send the request - response = LivestreamServiceRestTransport._GetChannel._get_response( + response = LivestreamServiceRestTransport._GetClip._get_response( self._host, metadata, query_params, @@ -3448,21 +4182,21 @@ def __call__( raise core_exceptions.from_http_response(response) # Return the response - resp = resources.Channel() - pb_resp = resources.Channel.pb(resp) + resp = resources.Clip() + pb_resp = resources.Clip.pb(resp) json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_get_channel(resp) + resp = self._interceptor.post_get_clip(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_get_channel_with_metadata( + resp, _ = self._interceptor.post_get_clip_with_metadata( resp, response_metadata ) if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( logging.DEBUG ): # pragma: NO COVER try: - response_payload = resources.Channel.to_json(response) + response_payload = resources.Clip.to_json(response) except: response_payload = None http_response = { @@ -3471,21 +4205,22 @@ def __call__( "status": response.status_code, } _LOGGER.debug( - "Received response for google.cloud.video.livestream_v1.LivestreamServiceClient.get_channel", + "Received response for google.cloud.video.livestream_v1.LivestreamServiceClient.get_clip", extra={ "serviceName": "google.cloud.video.livestream.v1.LivestreamService", - "rpcName": "GetChannel", + "rpcName": "GetClip", "metadata": http_response["headers"], "httpResponse": http_response, }, ) return resp - class _GetClip( - _BaseLivestreamServiceRestTransport._BaseGetClip, LivestreamServiceRestStub + class _GetDvrSession( + _BaseLivestreamServiceRestTransport._BaseGetDvrSession, + LivestreamServiceRestStub, ): def __hash__(self): - return hash("LivestreamServiceRestTransport.GetClip") + return hash("LivestreamServiceRestTransport.GetDvrSession") @staticmethod def _get_response( @@ -3511,18 +4246,18 @@ def _get_response( def __call__( self, - request: service.GetClipRequest, + request: service.GetDvrSessionRequest, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> resources.Clip: - r"""Call the get clip method over HTTP. + ) -> resources.DvrSession: + r"""Call the get dvr session method over HTTP. Args: - request (~.service.GetClipRequest): + request (~.service.GetDvrSessionRequest): The request object. Request message for - "LivestreamService.GetClip". + "LivestreamService.GetDvrSession". retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -3532,29 +4267,26 @@ def __call__( be of type `bytes`. Returns: - ~.resources.Clip: - Clip is a sub-resource under channel. - Each clip represents a clipping - operation that generates a VOD playlist - from its channel given a set of - timestamp ranges. + ~.resources.DvrSession: + DvrSession is a sub-resource under + channel. Each DvrSession represents a + DVR recording of the live stream for a + specific time range. """ http_options = ( - _BaseLivestreamServiceRestTransport._BaseGetClip._get_http_options() + _BaseLivestreamServiceRestTransport._BaseGetDvrSession._get_http_options() ) - request, metadata = self._interceptor.pre_get_clip(request, metadata) - transcoded_request = _BaseLivestreamServiceRestTransport._BaseGetClip._get_transcoded_request( + request, metadata = self._interceptor.pre_get_dvr_session(request, metadata) + transcoded_request = _BaseLivestreamServiceRestTransport._BaseGetDvrSession._get_transcoded_request( http_options, request ) # Jsonify the query params - query_params = ( - _BaseLivestreamServiceRestTransport._BaseGetClip._get_query_params_json( - transcoded_request - ) + query_params = _BaseLivestreamServiceRestTransport._BaseGetDvrSession._get_query_params_json( + transcoded_request ) if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( @@ -3575,17 +4307,17 @@ def __call__( "headers": dict(metadata), } _LOGGER.debug( - f"Sending request for google.cloud.video.livestream_v1.LivestreamServiceClient.GetClip", + f"Sending request for google.cloud.video.livestream_v1.LivestreamServiceClient.GetDvrSession", extra={ "serviceName": "google.cloud.video.livestream.v1.LivestreamService", - "rpcName": "GetClip", + "rpcName": "GetDvrSession", "httpRequest": http_request, "metadata": http_request["headers"], }, ) # Send the request - response = LivestreamServiceRestTransport._GetClip._get_response( + response = LivestreamServiceRestTransport._GetDvrSession._get_response( self._host, metadata, query_params, @@ -3600,21 +4332,21 @@ def __call__( raise core_exceptions.from_http_response(response) # Return the response - resp = resources.Clip() - pb_resp = resources.Clip.pb(resp) + resp = resources.DvrSession() + pb_resp = resources.DvrSession.pb(resp) json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_get_clip(resp) + resp = self._interceptor.post_get_dvr_session(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_get_clip_with_metadata( + resp, _ = self._interceptor.post_get_dvr_session_with_metadata( resp, response_metadata ) if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( logging.DEBUG ): # pragma: NO COVER try: - response_payload = resources.Clip.to_json(response) + response_payload = resources.DvrSession.to_json(response) except: response_payload = None http_response = { @@ -3623,10 +4355,10 @@ def __call__( "status": response.status_code, } _LOGGER.debug( - "Received response for google.cloud.video.livestream_v1.LivestreamServiceClient.get_clip", + "Received response for google.cloud.video.livestream_v1.LivestreamServiceClient.get_dvr_session", extra={ "serviceName": "google.cloud.video.livestream.v1.LivestreamService", - "rpcName": "GetClip", + "rpcName": "GetDvrSession", "metadata": http_response["headers"], "httpResponse": http_response, }, @@ -4174,17 +4906,164 @@ def __call__( "headers": dict(metadata), } _LOGGER.debug( - f"Sending request for google.cloud.video.livestream_v1.LivestreamServiceClient.ListAssets", + f"Sending request for google.cloud.video.livestream_v1.LivestreamServiceClient.ListAssets", + extra={ + "serviceName": "google.cloud.video.livestream.v1.LivestreamService", + "rpcName": "ListAssets", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = LivestreamServiceRestTransport._ListAssets._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = service.ListAssetsResponse() + pb_resp = service.ListAssetsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_list_assets(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_list_assets_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = service.ListAssetsResponse.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.video.livestream_v1.LivestreamServiceClient.list_assets", + extra={ + "serviceName": "google.cloud.video.livestream.v1.LivestreamService", + "rpcName": "ListAssets", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _ListChannels( + _BaseLivestreamServiceRestTransport._BaseListChannels, LivestreamServiceRestStub + ): + def __hash__(self): + return hash("LivestreamServiceRestTransport.ListChannels") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: service.ListChannelsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> service.ListChannelsResponse: + r"""Call the list channels method over HTTP. + + Args: + request (~.service.ListChannelsRequest): + The request object. Request message for + "LivestreamService.ListChannels". + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.service.ListChannelsResponse: + Response message for + "LivestreamService.ListChannels". + + """ + + http_options = ( + _BaseLivestreamServiceRestTransport._BaseListChannels._get_http_options() + ) + + request, metadata = self._interceptor.pre_list_channels(request, metadata) + transcoded_request = _BaseLivestreamServiceRestTransport._BaseListChannels._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = _BaseLivestreamServiceRestTransport._BaseListChannels._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.video.livestream_v1.LivestreamServiceClient.ListChannels", extra={ "serviceName": "google.cloud.video.livestream.v1.LivestreamService", - "rpcName": "ListAssets", + "rpcName": "ListChannels", "httpRequest": http_request, "metadata": http_request["headers"], }, ) # Send the request - response = LivestreamServiceRestTransport._ListAssets._get_response( + response = LivestreamServiceRestTransport._ListChannels._get_response( self._host, metadata, query_params, @@ -4199,21 +5078,21 @@ def __call__( raise core_exceptions.from_http_response(response) # Return the response - resp = service.ListAssetsResponse() - pb_resp = service.ListAssetsResponse.pb(resp) + resp = service.ListChannelsResponse() + pb_resp = service.ListChannelsResponse.pb(resp) json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_list_assets(resp) + resp = self._interceptor.post_list_channels(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_list_assets_with_metadata( + resp, _ = self._interceptor.post_list_channels_with_metadata( resp, response_metadata ) if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( logging.DEBUG ): # pragma: NO COVER try: - response_payload = service.ListAssetsResponse.to_json(response) + response_payload = service.ListChannelsResponse.to_json(response) except: response_payload = None http_response = { @@ -4222,21 +5101,21 @@ def __call__( "status": response.status_code, } _LOGGER.debug( - "Received response for google.cloud.video.livestream_v1.LivestreamServiceClient.list_assets", + "Received response for google.cloud.video.livestream_v1.LivestreamServiceClient.list_channels", extra={ "serviceName": "google.cloud.video.livestream.v1.LivestreamService", - "rpcName": "ListAssets", + "rpcName": "ListChannels", "metadata": http_response["headers"], "httpResponse": http_response, }, ) return resp - class _ListChannels( - _BaseLivestreamServiceRestTransport._BaseListChannels, LivestreamServiceRestStub + class _ListClips( + _BaseLivestreamServiceRestTransport._BaseListClips, LivestreamServiceRestStub ): def __hash__(self): - return hash("LivestreamServiceRestTransport.ListChannels") + return hash("LivestreamServiceRestTransport.ListClips") @staticmethod def _get_response( @@ -4262,18 +5141,18 @@ def _get_response( def __call__( self, - request: service.ListChannelsRequest, + request: service.ListClipsRequest, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> service.ListChannelsResponse: - r"""Call the list channels method over HTTP. + ) -> service.ListClipsResponse: + r"""Call the list clips method over HTTP. Args: - request (~.service.ListChannelsRequest): + request (~.service.ListClipsRequest): The request object. Request message for - "LivestreamService.ListChannels". + "LivestreamService.ListClips". retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -4283,23 +5162,23 @@ def __call__( be of type `bytes`. Returns: - ~.service.ListChannelsResponse: + ~.service.ListClipsResponse: Response message for - "LivestreamService.ListChannels". + "LivestreamService.ListClips". """ http_options = ( - _BaseLivestreamServiceRestTransport._BaseListChannels._get_http_options() + _BaseLivestreamServiceRestTransport._BaseListClips._get_http_options() ) - request, metadata = self._interceptor.pre_list_channels(request, metadata) - transcoded_request = _BaseLivestreamServiceRestTransport._BaseListChannels._get_transcoded_request( + request, metadata = self._interceptor.pre_list_clips(request, metadata) + transcoded_request = _BaseLivestreamServiceRestTransport._BaseListClips._get_transcoded_request( http_options, request ) # Jsonify the query params - query_params = _BaseLivestreamServiceRestTransport._BaseListChannels._get_query_params_json( + query_params = _BaseLivestreamServiceRestTransport._BaseListClips._get_query_params_json( transcoded_request ) @@ -4321,17 +5200,17 @@ def __call__( "headers": dict(metadata), } _LOGGER.debug( - f"Sending request for google.cloud.video.livestream_v1.LivestreamServiceClient.ListChannels", + f"Sending request for google.cloud.video.livestream_v1.LivestreamServiceClient.ListClips", extra={ "serviceName": "google.cloud.video.livestream.v1.LivestreamService", - "rpcName": "ListChannels", + "rpcName": "ListClips", "httpRequest": http_request, "metadata": http_request["headers"], }, ) # Send the request - response = LivestreamServiceRestTransport._ListChannels._get_response( + response = LivestreamServiceRestTransport._ListClips._get_response( self._host, metadata, query_params, @@ -4346,21 +5225,21 @@ def __call__( raise core_exceptions.from_http_response(response) # Return the response - resp = service.ListChannelsResponse() - pb_resp = service.ListChannelsResponse.pb(resp) + resp = service.ListClipsResponse() + pb_resp = service.ListClipsResponse.pb(resp) json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_list_channels(resp) + resp = self._interceptor.post_list_clips(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_list_channels_with_metadata( + resp, _ = self._interceptor.post_list_clips_with_metadata( resp, response_metadata ) if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( logging.DEBUG ): # pragma: NO COVER try: - response_payload = service.ListChannelsResponse.to_json(response) + response_payload = service.ListClipsResponse.to_json(response) except: response_payload = None http_response = { @@ -4369,21 +5248,22 @@ def __call__( "status": response.status_code, } _LOGGER.debug( - "Received response for google.cloud.video.livestream_v1.LivestreamServiceClient.list_channels", + "Received response for google.cloud.video.livestream_v1.LivestreamServiceClient.list_clips", extra={ "serviceName": "google.cloud.video.livestream.v1.LivestreamService", - "rpcName": "ListChannels", + "rpcName": "ListClips", "metadata": http_response["headers"], "httpResponse": http_response, }, ) return resp - class _ListClips( - _BaseLivestreamServiceRestTransport._BaseListClips, LivestreamServiceRestStub + class _ListDvrSessions( + _BaseLivestreamServiceRestTransport._BaseListDvrSessions, + LivestreamServiceRestStub, ): def __hash__(self): - return hash("LivestreamServiceRestTransport.ListClips") + return hash("LivestreamServiceRestTransport.ListDvrSessions") @staticmethod def _get_response( @@ -4409,18 +5289,18 @@ def _get_response( def __call__( self, - request: service.ListClipsRequest, + request: service.ListDvrSessionsRequest, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> service.ListClipsResponse: - r"""Call the list clips method over HTTP. + ) -> service.ListDvrSessionsResponse: + r"""Call the list dvr sessions method over HTTP. Args: - request (~.service.ListClipsRequest): + request (~.service.ListDvrSessionsRequest): The request object. Request message for - "LivestreamService.ListClips". + "LivestreamService.ListDvrSessions". retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -4430,23 +5310,25 @@ def __call__( be of type `bytes`. Returns: - ~.service.ListClipsResponse: + ~.service.ListDvrSessionsResponse: Response message for - "LivestreamService.ListClips". + "LivestreamService.ListDvrSessions". """ http_options = ( - _BaseLivestreamServiceRestTransport._BaseListClips._get_http_options() + _BaseLivestreamServiceRestTransport._BaseListDvrSessions._get_http_options() ) - request, metadata = self._interceptor.pre_list_clips(request, metadata) - transcoded_request = _BaseLivestreamServiceRestTransport._BaseListClips._get_transcoded_request( + request, metadata = self._interceptor.pre_list_dvr_sessions( + request, metadata + ) + transcoded_request = _BaseLivestreamServiceRestTransport._BaseListDvrSessions._get_transcoded_request( http_options, request ) # Jsonify the query params - query_params = _BaseLivestreamServiceRestTransport._BaseListClips._get_query_params_json( + query_params = _BaseLivestreamServiceRestTransport._BaseListDvrSessions._get_query_params_json( transcoded_request ) @@ -4468,17 +5350,17 @@ def __call__( "headers": dict(metadata), } _LOGGER.debug( - f"Sending request for google.cloud.video.livestream_v1.LivestreamServiceClient.ListClips", + f"Sending request for google.cloud.video.livestream_v1.LivestreamServiceClient.ListDvrSessions", extra={ "serviceName": "google.cloud.video.livestream.v1.LivestreamService", - "rpcName": "ListClips", + "rpcName": "ListDvrSessions", "httpRequest": http_request, "metadata": http_request["headers"], }, ) # Send the request - response = LivestreamServiceRestTransport._ListClips._get_response( + response = LivestreamServiceRestTransport._ListDvrSessions._get_response( self._host, metadata, query_params, @@ -4493,21 +5375,21 @@ def __call__( raise core_exceptions.from_http_response(response) # Return the response - resp = service.ListClipsResponse() - pb_resp = service.ListClipsResponse.pb(resp) + resp = service.ListDvrSessionsResponse() + pb_resp = service.ListDvrSessionsResponse.pb(resp) json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_list_clips(resp) + resp = self._interceptor.post_list_dvr_sessions(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_list_clips_with_metadata( + resp, _ = self._interceptor.post_list_dvr_sessions_with_metadata( resp, response_metadata ) if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( logging.DEBUG ): # pragma: NO COVER try: - response_payload = service.ListClipsResponse.to_json(response) + response_payload = service.ListDvrSessionsResponse.to_json(response) except: response_payload = None http_response = { @@ -4516,10 +5398,10 @@ def __call__( "status": response.status_code, } _LOGGER.debug( - "Received response for google.cloud.video.livestream_v1.LivestreamServiceClient.list_clips", + "Received response for google.cloud.video.livestream_v1.LivestreamServiceClient.list_dvr_sessions", extra={ "serviceName": "google.cloud.video.livestream.v1.LivestreamService", - "rpcName": "ListClips", + "rpcName": "ListDvrSessions", "metadata": http_response["headers"], "httpResponse": http_response, }, @@ -5277,6 +6159,161 @@ def __call__( ) return resp + class _UpdateDvrSession( + _BaseLivestreamServiceRestTransport._BaseUpdateDvrSession, + LivestreamServiceRestStub, + ): + def __hash__(self): + return hash("LivestreamServiceRestTransport.UpdateDvrSession") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: service.UpdateDvrSessionRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + r"""Call the update dvr session method over HTTP. + + Args: + request (~.service.UpdateDvrSessionRequest): + The request object. Request message for + "LivestreamService.UpdateDvrSession". + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each 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 = ( + _BaseLivestreamServiceRestTransport._BaseUpdateDvrSession._get_http_options() + ) + + request, metadata = self._interceptor.pre_update_dvr_session( + request, metadata + ) + transcoded_request = _BaseLivestreamServiceRestTransport._BaseUpdateDvrSession._get_transcoded_request( + http_options, request + ) + + body = _BaseLivestreamServiceRestTransport._BaseUpdateDvrSession._get_request_body_json( + transcoded_request + ) + + # Jsonify the query params + query_params = _BaseLivestreamServiceRestTransport._BaseUpdateDvrSession._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.video.livestream_v1.LivestreamServiceClient.UpdateDvrSession", + extra={ + "serviceName": "google.cloud.video.livestream.v1.LivestreamService", + "rpcName": "UpdateDvrSession", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = LivestreamServiceRestTransport._UpdateDvrSession._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_update_dvr_session(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_update_dvr_session_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.video.livestream_v1.LivestreamServiceClient.update_dvr_session", + extra={ + "serviceName": "google.cloud.video.livestream.v1.LivestreamService", + "rpcName": "UpdateDvrSession", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + class _UpdateInput( _BaseLivestreamServiceRestTransport._BaseUpdateInput, LivestreamServiceRestStub ): @@ -5605,6 +6642,14 @@ def create_clip( # In C++ this would require a dynamic_cast return self._CreateClip(self._session, self._host, self._interceptor) # type: ignore + @property + def create_dvr_session( + self, + ) -> Callable[[service.CreateDvrSessionRequest], 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._CreateDvrSession(self._session, self._host, self._interceptor) # type: ignore + @property def create_event(self) -> Callable[[service.CreateEventRequest], resources.Event]: # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. @@ -5643,6 +6688,14 @@ def delete_clip( # In C++ this would require a dynamic_cast return self._DeleteClip(self._session, self._host, self._interceptor) # type: ignore + @property + def delete_dvr_session( + self, + ) -> Callable[[service.DeleteDvrSessionRequest], 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._DeleteDvrSession(self._session, self._host, self._interceptor) # type: ignore + @property def delete_event(self) -> Callable[[service.DeleteEventRequest], empty_pb2.Empty]: # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. @@ -5675,6 +6728,14 @@ def get_clip(self) -> Callable[[service.GetClipRequest], resources.Clip]: # In C++ this would require a dynamic_cast return self._GetClip(self._session, self._host, self._interceptor) # type: ignore + @property + def get_dvr_session( + self, + ) -> Callable[[service.GetDvrSessionRequest], resources.DvrSession]: + # 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._GetDvrSession(self._session, self._host, self._interceptor) # type: ignore + @property def get_event(self) -> Callable[[service.GetEventRequest], resources.Event]: # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. @@ -5717,6 +6778,14 @@ def list_clips( # In C++ this would require a dynamic_cast return self._ListClips(self._session, self._host, self._interceptor) # type: ignore + @property + def list_dvr_sessions( + self, + ) -> Callable[[service.ListDvrSessionsRequest], service.ListDvrSessionsResponse]: + # 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._ListDvrSessions(self._session, self._host, self._interceptor) # type: ignore + @property def list_events( self, @@ -5757,6 +6826,14 @@ def update_channel( # In C++ this would require a dynamic_cast return self._UpdateChannel(self._session, self._host, self._interceptor) # type: ignore + @property + def update_dvr_session( + self, + ) -> Callable[[service.UpdateDvrSessionRequest], 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._UpdateDvrSession(self._session, self._host, self._interceptor) # type: ignore + @property def update_input( self, diff --git a/packages/google-cloud-video-live-stream/google/cloud/video/live_stream_v1/services/livestream_service/transports/rest_base.py b/packages/google-cloud-video-live-stream/google/cloud/video/live_stream_v1/services/livestream_service/transports/rest_base.py index f8d33cc887be..50f977abd26b 100644 --- a/packages/google-cloud-video-live-stream/google/cloud/video/live_stream_v1/services/livestream_service/transports/rest_base.py +++ b/packages/google-cloud-video-live-stream/google/cloud/video/live_stream_v1/services/livestream_service/transports/rest_base.py @@ -267,6 +267,65 @@ def _get_query_params_json(transcoded_request): query_params["$alt"] = "json;enum-encoding=int" return query_params + class _BaseCreateDvrSession: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "dvrSessionId": "", + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1/{parent=projects/*/locations/*/channels/*}/dvrSessions", + "body": "dvr_session", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = service.CreateDvrSessionRequest.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( + _BaseLivestreamServiceRestTransport._BaseCreateDvrSession._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + class _BaseCreateEvent: def __hash__(self): # pragma: NO COVER return NotImplementedError("__hash__ must be implemented.") @@ -526,6 +585,53 @@ def _get_query_params_json(transcoded_request): query_params["$alt"] = "json;enum-encoding=int" return query_params + class _BaseDeleteDvrSession: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "delete", + "uri": "/v1/{name=projects/*/locations/*/channels/*/dvrSessions/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = service.DeleteDvrSessionRequest.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( + _BaseLivestreamServiceRestTransport._BaseDeleteDvrSession._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + class _BaseDeleteEvent: def __hash__(self): # pragma: NO COVER return NotImplementedError("__hash__ must be implemented.") @@ -761,6 +867,53 @@ def _get_query_params_json(transcoded_request): query_params["$alt"] = "json;enum-encoding=int" return query_params + class _BaseGetDvrSession: + 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=projects/*/locations/*/channels/*/dvrSessions/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = service.GetDvrSessionRequest.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( + _BaseLivestreamServiceRestTransport._BaseGetDvrSession._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + class _BaseGetEvent: def __hash__(self): # pragma: NO COVER return NotImplementedError("__hash__ must be implemented.") @@ -1043,6 +1196,53 @@ def _get_query_params_json(transcoded_request): query_params["$alt"] = "json;enum-encoding=int" return query_params + class _BaseListDvrSessions: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{parent=projects/*/locations/*/channels/*}/dvrSessions", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = service.ListDvrSessionsRequest.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( + _BaseLivestreamServiceRestTransport._BaseListDvrSessions._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + class _BaseListEvents: def __hash__(self): # pragma: NO COVER return NotImplementedError("__hash__ must be implemented.") @@ -1308,6 +1508,65 @@ def _get_query_params_json(transcoded_request): query_params["$alt"] = "json;enum-encoding=int" return query_params + class _BaseUpdateDvrSession: + 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/{dvr_session.name=projects/*/locations/*/channels/*/dvrSessions/*}", + "body": "dvr_session", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = service.UpdateDvrSessionRequest.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( + _BaseLivestreamServiceRestTransport._BaseUpdateDvrSession._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + class _BaseUpdateInput: def __hash__(self): # pragma: NO COVER return NotImplementedError("__hash__ must be implemented.") diff --git a/packages/google-cloud-video-live-stream/google/cloud/video/live_stream_v1/types/__init__.py b/packages/google-cloud-video-live-stream/google/cloud/video/live_stream_v1/types/__init__.py index af9c67ba39ea..57bf42aac0ca 100644 --- a/packages/google-cloud-video-live-stream/google/cloud/video/live_stream_v1/types/__init__.py +++ b/packages/google-cloud-video-live-stream/google/cloud/video/live_stream_v1/types/__init__.py @@ -31,6 +31,7 @@ AudioStreamProperty, Channel, Clip, + DvrSession, Encryption, Event, Input, @@ -43,6 +44,7 @@ Pool, RetentionConfig, StaticOverlay, + TimeInterval, VideoFormat, VideoStreamProperty, ) @@ -51,16 +53,19 @@ CreateAssetRequest, CreateChannelRequest, CreateClipRequest, + CreateDvrSessionRequest, CreateEventRequest, CreateInputRequest, DeleteAssetRequest, DeleteChannelRequest, DeleteClipRequest, + DeleteDvrSessionRequest, DeleteEventRequest, DeleteInputRequest, GetAssetRequest, GetChannelRequest, GetClipRequest, + GetDvrSessionRequest, GetEventRequest, GetInputRequest, GetPoolRequest, @@ -70,6 +75,8 @@ ListChannelsResponse, ListClipsRequest, ListClipsResponse, + ListDvrSessionsRequest, + ListDvrSessionsResponse, ListEventsRequest, ListEventsResponse, ListInputsRequest, @@ -78,6 +85,7 @@ StartChannelRequest, StopChannelRequest, UpdateChannelRequest, + UpdateDvrSessionRequest, UpdateInputRequest, UpdatePoolRequest, ) @@ -98,6 +106,7 @@ "AudioStreamProperty", "Channel", "Clip", + "DvrSession", "Encryption", "Event", "Input", @@ -110,22 +119,26 @@ "Pool", "RetentionConfig", "StaticOverlay", + "TimeInterval", "VideoFormat", "VideoStreamProperty", "ChannelOperationResponse", "CreateAssetRequest", "CreateChannelRequest", "CreateClipRequest", + "CreateDvrSessionRequest", "CreateEventRequest", "CreateInputRequest", "DeleteAssetRequest", "DeleteChannelRequest", "DeleteClipRequest", + "DeleteDvrSessionRequest", "DeleteEventRequest", "DeleteInputRequest", "GetAssetRequest", "GetChannelRequest", "GetClipRequest", + "GetDvrSessionRequest", "GetEventRequest", "GetInputRequest", "GetPoolRequest", @@ -135,6 +148,8 @@ "ListChannelsResponse", "ListClipsRequest", "ListClipsResponse", + "ListDvrSessionsRequest", + "ListDvrSessionsResponse", "ListEventsRequest", "ListEventsResponse", "ListInputsRequest", @@ -143,6 +158,7 @@ "StartChannelRequest", "StopChannelRequest", "UpdateChannelRequest", + "UpdateDvrSessionRequest", "UpdateInputRequest", "UpdatePoolRequest", ) diff --git a/packages/google-cloud-video-live-stream/google/cloud/video/live_stream_v1/types/resources.py b/packages/google-cloud-video-live-stream/google/cloud/video/live_stream_v1/types/resources.py index 67c1a8c93385..7d2b9a79159e 100644 --- a/packages/google-cloud-video-live-stream/google/cloud/video/live_stream_v1/types/resources.py +++ b/packages/google-cloud-video-live-stream/google/cloud/video/live_stream_v1/types/resources.py @@ -43,6 +43,8 @@ "InputAttachment", "Event", "Clip", + "TimeInterval", + "DvrSession", "Asset", "Encryption", "Pool", @@ -1079,7 +1081,7 @@ class Clip(proto.Message): Attributes: name (str): The resource name of the clip, in the following format: - ``projects/{project}/locations/{location}/channels/{c}/clips/{clipId}``. + ``projects/{project}/locations/{location}/channels/{channelId}/clips/{clipId}``. ``{clipId}`` is a user-specified resource id that conforms to the following criteria: @@ -1118,6 +1120,9 @@ class Clip(proto.Message): clip_manifests (MutableSequence[google.cloud.video.live_stream_v1.types.Clip.ClipManifest]): Required. A list of clip manifests. Currently only one clip manifest is allowed. + output_type (google.cloud.video.live_stream_v1.types.Clip.OutputType): + Optional. OutputType of the clip. If not + specified, the default value is MANIFEST. """ class State(proto.Enum): @@ -1145,6 +1150,22 @@ class State(proto.Enum): SUCCEEDED = 3 FAILED = 4 + class OutputType(proto.Enum): + r"""OutputType represents the output type of the clip. + + Values: + OUTPUT_TYPE_UNSPECIFIED (0): + OutputType is not specified. + MANIFEST (1): + OutputType is a VOD manifest. This is the + default value. + MP4 (2): + OutputType is an MP4 file. + """ + OUTPUT_TYPE_UNSPECIFIED = 0 + MANIFEST = 1 + MP4 = 2 + class TimeSlice(proto.Message): r"""TimeSlice represents a tuple of Unix epoch timestamps that specifies a time range. @@ -1265,6 +1286,215 @@ class ClipManifest(proto.Message): number=12, message=ClipManifest, ) + output_type: OutputType = proto.Field( + proto.ENUM, + number=13, + enum=OutputType, + ) + + +class TimeInterval(proto.Message): + r"""TimeInterval represents a time interval. + + Attributes: + start_time (google.protobuf.timestamp_pb2.Timestamp): + Optional. The start time of the interval. + end_time (google.protobuf.timestamp_pb2.Timestamp): + Optional. The end time of the interval. + """ + + start_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=1, + message=timestamp_pb2.Timestamp, + ) + end_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + + +class DvrSession(proto.Message): + r"""DvrSession is a sub-resource under channel. Each DvrSession + represents a DVR recording of the live stream for a specific + time range. + + Attributes: + name (str): + Identifier. The resource name of the DVR session, in the + following format: + ``projects/{project}/locations/{location}/channels/{channelId}/dvrSessions/{dvrSessionId}``. + ``{dvrSessionId}`` is a user-specified resource id that + conforms to the following criteria: + + 1. 1 character minimum, 63 characters maximum + 2. Only contains letters, digits, underscores, and hyphens + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The creation time. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The update time. + labels (MutableMapping[str, str]): + Optional. User-defined key/value metadata. + state (google.cloud.video.live_stream_v1.types.DvrSession.State): + Output only. The state of the clip. + error (google.rpc.status_pb2.Status): + Output only. An error object that describes the reason for + the failure. This property only presents when ``state`` is + ``FAILED``. + dvr_manifests (MutableSequence[google.cloud.video.live_stream_v1.types.DvrSession.DvrManifest]): + Required. A list of DVR manifests. Currently + only one DVR manifest is allowed. + dvr_windows (MutableSequence[google.cloud.video.live_stream_v1.types.DvrSession.DvrWindow]): + Required. The specified ranges of segments to + generate a DVR recording. + """ + + class State(proto.Enum): + r"""State of the DVR session. + + Values: + STATE_UNSPECIFIED (0): + State is not specified. + PENDING (1): + The operation is pending to be picked up by + the server. + UPDATING (2): + The session is being updated. + SCHEDULED (3): + The session is scheduled and waiting for the + start time. + LIVE (4): + The session is currently in progress and the outputs are + available in the specified Cloud Storage bucket. For + additional information, see the ``dvr_manifests.output_uri`` + field. + FINISHED (5): + Outputs are available in the specified Cloud Storage bucket. + For additional information, see the + ``dvr_manifests.output_uri`` field. + FAILED (6): + The operation has failed. For additional information, see + the ``error`` field. + DELETING (7): + The session is being deleted. + POST_PROCESSING (8): + The session is being post processed. + COOLDOWN (9): + The session is in cooldown. The cooldown + period lasts for 60 seconds. When the DVR + session is updated by the user to have a new end + time that is likely already in the past, the DVR + manifest will end as soon as possible and the + DVR session will move to this state. This is + done to prevent the players to receive a + manifest update that removes a segment that has + already been played. After the cooldown period + ends, a new manifest is generated that honors + the new end time. + STOPPING (10): + The session is being stopped. The session + will move to STOPPING state, if the parent + channel is updated. + """ + STATE_UNSPECIFIED = 0 + PENDING = 1 + UPDATING = 2 + SCHEDULED = 3 + LIVE = 4 + FINISHED = 5 + FAILED = 6 + DELETING = 7 + POST_PROCESSING = 8 + COOLDOWN = 9 + STOPPING = 10 + + class DvrManifest(proto.Message): + r"""DvrManifest identifies a source manifest and specifies a file + name for the generated DVR manifest. + + Attributes: + manifest_key (str): + Required. A unique key that identifies a manifest config in + the parent channel. This key is the same as + ``channel.manifests.key`` for the selected manifest. + output_uri (str): + Output only. The output URI of the DVR manifest. The DVR + output will be placed in a directory named + ``dvr/dvrSessionId/`` under the parent channel's output uri. + Format: + {channel.output.uri}/dvr/{dvrSessionId}/{channel.manifests.fileName} + Example: gs://my-bucket/outputs/dvr/my-dvr-session/main.m3u8 + """ + + manifest_key: str = proto.Field( + proto.STRING, + number=1, + ) + output_uri: str = proto.Field( + proto.STRING, + number=2, + ) + + class DvrWindow(proto.Message): + r"""DvrWindow represents a DVR window. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + time_interval (google.cloud.video.live_stream_v1.types.TimeInterval): + A time interval in the form of a tuple of + Unix epoch time. + + This field is a member of `oneof`_ ``kind``. + """ + + time_interval: "TimeInterval" = proto.Field( + proto.MESSAGE, + number=1, + oneof="kind", + message="TimeInterval", + ) + + name: str = proto.Field( + proto.STRING, + number=1, + ) + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=3, + message=timestamp_pb2.Timestamp, + ) + labels: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=4, + ) + state: State = proto.Field( + proto.ENUM, + number=5, + enum=State, + ) + error: status_pb2.Status = proto.Field( + proto.MESSAGE, + number=6, + message=status_pb2.Status, + ) + dvr_manifests: MutableSequence[DvrManifest] = proto.RepeatedField( + proto.MESSAGE, + number=7, + message=DvrManifest, + ) + dvr_windows: MutableSequence[DvrWindow] = proto.RepeatedField( + proto.MESSAGE, + number=8, + message=DvrWindow, + ) class Asset(proto.Message): diff --git a/packages/google-cloud-video-live-stream/google/cloud/video/live_stream_v1/types/service.py b/packages/google-cloud-video-live-stream/google/cloud/video/live_stream_v1/types/service.py index 1d10aea7c1f7..29780e7a6103 100644 --- a/packages/google-cloud-video-live-stream/google/cloud/video/live_stream_v1/types/service.py +++ b/packages/google-cloud-video-live-stream/google/cloud/video/live_stream_v1/types/service.py @@ -56,6 +56,12 @@ "GetClipRequest", "CreateClipRequest", "DeleteClipRequest", + "ListDvrSessionsRequest", + "ListDvrSessionsResponse", + "GetDvrSessionRequest", + "CreateDvrSessionRequest", + "DeleteDvrSessionRequest", + "UpdateDvrSessionRequest", "OperationMetadata", "GetPoolRequest", "UpdatePoolRequest", @@ -758,6 +764,7 @@ class UpdateInputRequest(proto.Message): in the Input resource by the update. You can only update the following fields: + - ```tier`` `__ - ```preprocessingConfig`` `__ - ```securityRules`` `__ @@ -1177,6 +1184,241 @@ class DeleteClipRequest(proto.Message): ) +class ListDvrSessionsRequest(proto.Message): + r"""Request message for "LivestreamService.ListDvrSessions". + + Attributes: + parent (str): + Required. Parent value for + ListDvrSessionsRequest + page_size (int): + Optional. Requested page size. Server may + return fewer items than requested. If + unspecified, server will pick an appropriate + default. + page_token (str): + Optional. A token identifying a page of + results the server should return. + filter (str): + Optional. Filtering results + order_by (str): + Optional. Hint for how to order the results + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + page_size: int = proto.Field( + proto.INT32, + number=2, + ) + page_token: str = proto.Field( + proto.STRING, + number=3, + ) + filter: str = proto.Field( + proto.STRING, + number=4, + ) + order_by: str = proto.Field( + proto.STRING, + number=5, + ) + + +class ListDvrSessionsResponse(proto.Message): + r"""Response message for "LivestreamService.ListDvrSessions". + + Attributes: + dvr_sessions (MutableSequence[google.cloud.video.live_stream_v1.types.DvrSession]): + The list of DVR sessions + next_page_token (str): + A token identifying a page of results the + server should return. + unreachable (MutableSequence[str]): + Locations that could not be reached. + """ + + @property + def raw_page(self): + return self + + dvr_sessions: MutableSequence[resources.DvrSession] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=resources.DvrSession, + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + unreachable: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=3, + ) + + +class GetDvrSessionRequest(proto.Message): + r"""Request message for "LivestreamService.GetDvrSession". + + Attributes: + name (str): + Required. Name of the resource, in the following form: + ``projects/{project}/locations/{location}/channels/{channelId}/dvrSessions/{dvrSessionId}``. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class CreateDvrSessionRequest(proto.Message): + r"""Request message for "LivestreamService.CreateDvrSession". + + Attributes: + parent (str): + Required. The parent resource name, in the following form: + ``projects/{project}/locations/{location}/channels/{channelId}``. + dvr_session_id (str): + Required. Id of the requesting object in the + following form: + + 1. 1 character minimum, 63 characters maximum + 2. Only contains letters, digits, underscores, + and hyphens + dvr_session (google.cloud.video.live_stream_v1.types.DvrSession): + Required. The resource being created + request_id (str): + Optional. An optional request ID to identify + requests. Specify a unique request ID so that if + you must retry your request, the server will + know to ignore the request if it has already + been completed. The server will guarantee that + for at least 60 minutes since the first request. + + For example, consider a situation where you make + an initial request and the request times out. If + you make the request again with the same request + ID, the server can check if original operation + with the same request ID was received, and if + so, will ignore the second request. This + prevents clients from accidentally creating + duplicate commitments. + + The request ID must be a valid UUID with the + exception that zero UUID is not supported + (00000000-0000-0000-0000-000000000000). + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + dvr_session_id: str = proto.Field( + proto.STRING, + number=2, + ) + dvr_session: resources.DvrSession = proto.Field( + proto.MESSAGE, + number=3, + message=resources.DvrSession, + ) + request_id: str = proto.Field( + proto.STRING, + number=4, + ) + + +class DeleteDvrSessionRequest(proto.Message): + r"""Request message for "LivestreamService.DeleteDvrSession". + + Attributes: + name (str): + Required. The name of the event resource, in the form of: + ``projects/{project}/locations/{location}/channels/{channelId}/dvrSessions/{dvrSessionId}``. + request_id (str): + Optional. A request ID to identify requests. Specify a + unique request ID so that if you must retry your request, + the server will know to ignore the request if it has already + been completed. The server will guarantee that for at least + 60 minutes since the first request. + + For example, consider a situation where you make an initial + request and the request times out. If you make the request + again with the same request ID, the server can check if + original operation with the same request ID was received, + and if so, will ignore the second request. This prevents + clients from accidentally creating duplicate commitments. + + The request ID must be a valid UUID with the exception that + zero UUID is not supported + ``(00000000-0000-0000-0000-000000000000)``. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + request_id: str = proto.Field( + proto.STRING, + number=2, + ) + + +class UpdateDvrSessionRequest(proto.Message): + r"""Request message for "LivestreamService.UpdateDvrSession". + + Attributes: + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. Field mask is used to specify the fields to be + overwritten in the DvrSession resource by the update. You + can only update the following fields: + + - ``dvrWindows`` + + The fields specified in the update_mask are relative to the + resource, not the full request. A field will be overwritten + if it is in the mask. + dvr_session (google.cloud.video.live_stream_v1.types.DvrSession): + Required. The DVR session resource to be + updated. + request_id (str): + Optional. A request ID to identify requests. Specify a + unique request ID so that if you must retry your request, + the server will know to ignore the request if it has already + been completed. The server will guarantee that for at least + 60 minutes since the first request. + + For example, consider a situation where you make an initial + request and the request times out. If you make the request + again with the same request ID, the server can check if + original operation with the same request ID was received, + and if so, will ignore the second request. This prevents + clients from accidentally creating duplicate commitments. + + The request ID must be a valid UUID with the exception that + zero UUID is not supported + ``(00000000-0000-0000-0000-000000000000)``. + """ + + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=1, + message=field_mask_pb2.FieldMask, + ) + dvr_session: resources.DvrSession = proto.Field( + proto.MESSAGE, + number=2, + message=resources.DvrSession, + ) + request_id: str = proto.Field( + proto.STRING, + number=3, + ) + + class OperationMetadata(proto.Message): r"""Represents the metadata of the long-running operation. @@ -1196,9 +1438,11 @@ class OperationMetadata(proto.Message): requested_cancellation (bool): Output only. Identifies whether the user has requested cancellation of the operation. Operations that have - successfully been cancelled have [Operation.error][] value - with a [google.rpc.Status.code][google.rpc.Status.code] of - 1, corresponding to ``Code.CANCELLED``. + successfully been cancelled have + [google.longrunning.Operation.error][google.longrunning.Operation.error] + value with a + [google.rpc.Status.code][google.rpc.Status.code] of 1, + corresponding to ``Code.CANCELLED``. api_version (str): Output only. API version used to start the operation. diff --git a/packages/google-cloud-video-live-stream/samples/generated_samples/livestream_v1_generated_livestream_service_create_dvr_session_async.py b/packages/google-cloud-video-live-stream/samples/generated_samples/livestream_v1_generated_livestream_service_create_dvr_session_async.py new file mode 100644 index 000000000000..f4156d502eea --- /dev/null +++ b/packages/google-cloud-video-live-stream/samples/generated_samples/livestream_v1_generated_livestream_service_create_dvr_session_async.py @@ -0,0 +1,61 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateDvrSession +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-video-live-stream + + +# [START livestream_v1_generated_LivestreamService_CreateDvrSession_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.video import live_stream_v1 + + +async def sample_create_dvr_session(): + # Create a client + client = live_stream_v1.LivestreamServiceAsyncClient() + + # Initialize request argument(s) + dvr_session = live_stream_v1.DvrSession() + dvr_session.dvr_manifests.manifest_key = "manifest_key_value" + + request = live_stream_v1.CreateDvrSessionRequest( + parent="parent_value", + dvr_session_id="dvr_session_id_value", + dvr_session=dvr_session, + ) + + # Make the request + operation = client.create_dvr_session(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END livestream_v1_generated_LivestreamService_CreateDvrSession_async] diff --git a/packages/google-cloud-video-live-stream/samples/generated_samples/livestream_v1_generated_livestream_service_create_dvr_session_sync.py b/packages/google-cloud-video-live-stream/samples/generated_samples/livestream_v1_generated_livestream_service_create_dvr_session_sync.py new file mode 100644 index 000000000000..67977fa1cbac --- /dev/null +++ b/packages/google-cloud-video-live-stream/samples/generated_samples/livestream_v1_generated_livestream_service_create_dvr_session_sync.py @@ -0,0 +1,61 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateDvrSession +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-video-live-stream + + +# [START livestream_v1_generated_LivestreamService_CreateDvrSession_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.video import live_stream_v1 + + +def sample_create_dvr_session(): + # Create a client + client = live_stream_v1.LivestreamServiceClient() + + # Initialize request argument(s) + dvr_session = live_stream_v1.DvrSession() + dvr_session.dvr_manifests.manifest_key = "manifest_key_value" + + request = live_stream_v1.CreateDvrSessionRequest( + parent="parent_value", + dvr_session_id="dvr_session_id_value", + dvr_session=dvr_session, + ) + + # Make the request + operation = client.create_dvr_session(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END livestream_v1_generated_LivestreamService_CreateDvrSession_sync] diff --git a/packages/google-cloud-video-live-stream/samples/generated_samples/livestream_v1_generated_livestream_service_delete_dvr_session_async.py b/packages/google-cloud-video-live-stream/samples/generated_samples/livestream_v1_generated_livestream_service_delete_dvr_session_async.py new file mode 100644 index 000000000000..9ec9358b2a71 --- /dev/null +++ b/packages/google-cloud-video-live-stream/samples/generated_samples/livestream_v1_generated_livestream_service_delete_dvr_session_async.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteDvrSession +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-video-live-stream + + +# [START livestream_v1_generated_LivestreamService_DeleteDvrSession_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.video import live_stream_v1 + + +async def sample_delete_dvr_session(): + # Create a client + client = live_stream_v1.LivestreamServiceAsyncClient() + + # Initialize request argument(s) + request = live_stream_v1.DeleteDvrSessionRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_dvr_session(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END livestream_v1_generated_LivestreamService_DeleteDvrSession_async] diff --git a/packages/google-cloud-video-live-stream/samples/generated_samples/livestream_v1_generated_livestream_service_delete_dvr_session_sync.py b/packages/google-cloud-video-live-stream/samples/generated_samples/livestream_v1_generated_livestream_service_delete_dvr_session_sync.py new file mode 100644 index 000000000000..a564cced7d4c --- /dev/null +++ b/packages/google-cloud-video-live-stream/samples/generated_samples/livestream_v1_generated_livestream_service_delete_dvr_session_sync.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteDvrSession +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-video-live-stream + + +# [START livestream_v1_generated_LivestreamService_DeleteDvrSession_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.video import live_stream_v1 + + +def sample_delete_dvr_session(): + # Create a client + client = live_stream_v1.LivestreamServiceClient() + + # Initialize request argument(s) + request = live_stream_v1.DeleteDvrSessionRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_dvr_session(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END livestream_v1_generated_LivestreamService_DeleteDvrSession_sync] diff --git a/packages/google-cloud-video-live-stream/samples/generated_samples/livestream_v1_generated_livestream_service_get_dvr_session_async.py b/packages/google-cloud-video-live-stream/samples/generated_samples/livestream_v1_generated_livestream_service_get_dvr_session_async.py new file mode 100644 index 000000000000..0dbe4ef105c7 --- /dev/null +++ b/packages/google-cloud-video-live-stream/samples/generated_samples/livestream_v1_generated_livestream_service_get_dvr_session_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetDvrSession +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-video-live-stream + + +# [START livestream_v1_generated_LivestreamService_GetDvrSession_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.video import live_stream_v1 + + +async def sample_get_dvr_session(): + # Create a client + client = live_stream_v1.LivestreamServiceAsyncClient() + + # Initialize request argument(s) + request = live_stream_v1.GetDvrSessionRequest( + name="name_value", + ) + + # Make the request + response = await client.get_dvr_session(request=request) + + # Handle the response + print(response) + +# [END livestream_v1_generated_LivestreamService_GetDvrSession_async] diff --git a/packages/google-cloud-video-live-stream/samples/generated_samples/livestream_v1_generated_livestream_service_get_dvr_session_sync.py b/packages/google-cloud-video-live-stream/samples/generated_samples/livestream_v1_generated_livestream_service_get_dvr_session_sync.py new file mode 100644 index 000000000000..863734b72950 --- /dev/null +++ b/packages/google-cloud-video-live-stream/samples/generated_samples/livestream_v1_generated_livestream_service_get_dvr_session_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetDvrSession +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-video-live-stream + + +# [START livestream_v1_generated_LivestreamService_GetDvrSession_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.video import live_stream_v1 + + +def sample_get_dvr_session(): + # Create a client + client = live_stream_v1.LivestreamServiceClient() + + # Initialize request argument(s) + request = live_stream_v1.GetDvrSessionRequest( + name="name_value", + ) + + # Make the request + response = client.get_dvr_session(request=request) + + # Handle the response + print(response) + +# [END livestream_v1_generated_LivestreamService_GetDvrSession_sync] diff --git a/packages/google-cloud-video-live-stream/samples/generated_samples/livestream_v1_generated_livestream_service_list_dvr_sessions_async.py b/packages/google-cloud-video-live-stream/samples/generated_samples/livestream_v1_generated_livestream_service_list_dvr_sessions_async.py new file mode 100644 index 000000000000..d2eea872df0f --- /dev/null +++ b/packages/google-cloud-video-live-stream/samples/generated_samples/livestream_v1_generated_livestream_service_list_dvr_sessions_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListDvrSessions +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-video-live-stream + + +# [START livestream_v1_generated_LivestreamService_ListDvrSessions_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.video import live_stream_v1 + + +async def sample_list_dvr_sessions(): + # Create a client + client = live_stream_v1.LivestreamServiceAsyncClient() + + # Initialize request argument(s) + request = live_stream_v1.ListDvrSessionsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_dvr_sessions(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END livestream_v1_generated_LivestreamService_ListDvrSessions_async] diff --git a/packages/google-cloud-video-live-stream/samples/generated_samples/livestream_v1_generated_livestream_service_list_dvr_sessions_sync.py b/packages/google-cloud-video-live-stream/samples/generated_samples/livestream_v1_generated_livestream_service_list_dvr_sessions_sync.py new file mode 100644 index 000000000000..0e54022e7550 --- /dev/null +++ b/packages/google-cloud-video-live-stream/samples/generated_samples/livestream_v1_generated_livestream_service_list_dvr_sessions_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListDvrSessions +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-video-live-stream + + +# [START livestream_v1_generated_LivestreamService_ListDvrSessions_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.video import live_stream_v1 + + +def sample_list_dvr_sessions(): + # Create a client + client = live_stream_v1.LivestreamServiceClient() + + # Initialize request argument(s) + request = live_stream_v1.ListDvrSessionsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_dvr_sessions(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END livestream_v1_generated_LivestreamService_ListDvrSessions_sync] diff --git a/packages/google-cloud-video-live-stream/samples/generated_samples/livestream_v1_generated_livestream_service_update_dvr_session_async.py b/packages/google-cloud-video-live-stream/samples/generated_samples/livestream_v1_generated_livestream_service_update_dvr_session_async.py new file mode 100644 index 000000000000..a8f69c809fc7 --- /dev/null +++ b/packages/google-cloud-video-live-stream/samples/generated_samples/livestream_v1_generated_livestream_service_update_dvr_session_async.py @@ -0,0 +1,59 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateDvrSession +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-video-live-stream + + +# [START livestream_v1_generated_LivestreamService_UpdateDvrSession_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.video import live_stream_v1 + + +async def sample_update_dvr_session(): + # Create a client + client = live_stream_v1.LivestreamServiceAsyncClient() + + # Initialize request argument(s) + dvr_session = live_stream_v1.DvrSession() + dvr_session.dvr_manifests.manifest_key = "manifest_key_value" + + request = live_stream_v1.UpdateDvrSessionRequest( + dvr_session=dvr_session, + ) + + # Make the request + operation = client.update_dvr_session(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END livestream_v1_generated_LivestreamService_UpdateDvrSession_async] diff --git a/packages/google-cloud-video-live-stream/samples/generated_samples/livestream_v1_generated_livestream_service_update_dvr_session_sync.py b/packages/google-cloud-video-live-stream/samples/generated_samples/livestream_v1_generated_livestream_service_update_dvr_session_sync.py new file mode 100644 index 000000000000..dcdea71d8bed --- /dev/null +++ b/packages/google-cloud-video-live-stream/samples/generated_samples/livestream_v1_generated_livestream_service_update_dvr_session_sync.py @@ -0,0 +1,59 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateDvrSession +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-video-live-stream + + +# [START livestream_v1_generated_LivestreamService_UpdateDvrSession_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.video import live_stream_v1 + + +def sample_update_dvr_session(): + # Create a client + client = live_stream_v1.LivestreamServiceClient() + + # Initialize request argument(s) + dvr_session = live_stream_v1.DvrSession() + dvr_session.dvr_manifests.manifest_key = "manifest_key_value" + + request = live_stream_v1.UpdateDvrSessionRequest( + dvr_session=dvr_session, + ) + + # Make the request + operation = client.update_dvr_session(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END livestream_v1_generated_LivestreamService_UpdateDvrSession_sync] diff --git a/packages/google-cloud-video-live-stream/samples/generated_samples/snippet_metadata_google.cloud.video.livestream.v1.json b/packages/google-cloud-video-live-stream/samples/generated_samples/snippet_metadata_google.cloud.video.livestream.v1.json index 6c0ad77a25a4..158b160f6b4e 100644 --- a/packages/google-cloud-video-live-stream/samples/generated_samples/snippet_metadata_google.cloud.video.livestream.v1.json +++ b/packages/google-cloud-video-live-stream/samples/generated_samples/snippet_metadata_google.cloud.video.livestream.v1.json @@ -542,6 +542,183 @@ ], "title": "livestream_v1_generated_livestream_service_create_clip_sync.py" }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.video.live_stream_v1.LivestreamServiceAsyncClient", + "shortName": "LivestreamServiceAsyncClient" + }, + "fullName": "google.cloud.video.live_stream_v1.LivestreamServiceAsyncClient.create_dvr_session", + "method": { + "fullName": "google.cloud.video.livestream.v1.LivestreamService.CreateDvrSession", + "service": { + "fullName": "google.cloud.video.livestream.v1.LivestreamService", + "shortName": "LivestreamService" + }, + "shortName": "CreateDvrSession" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.video.live_stream_v1.types.CreateDvrSessionRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "dvr_session", + "type": "google.cloud.video.live_stream_v1.types.DvrSession" + }, + { + "name": "dvr_session_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "create_dvr_session" + }, + "description": "Sample for CreateDvrSession", + "file": "livestream_v1_generated_livestream_service_create_dvr_session_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "livestream_v1_generated_LivestreamService_CreateDvrSession_async", + "segments": [ + { + "end": 60, + "start": 27, + "type": "FULL" + }, + { + "end": 60, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 50, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 57, + "start": 51, + "type": "REQUEST_EXECUTION" + }, + { + "end": 61, + "start": 58, + "type": "RESPONSE_HANDLING" + } + ], + "title": "livestream_v1_generated_livestream_service_create_dvr_session_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.video.live_stream_v1.LivestreamServiceClient", + "shortName": "LivestreamServiceClient" + }, + "fullName": "google.cloud.video.live_stream_v1.LivestreamServiceClient.create_dvr_session", + "method": { + "fullName": "google.cloud.video.livestream.v1.LivestreamService.CreateDvrSession", + "service": { + "fullName": "google.cloud.video.livestream.v1.LivestreamService", + "shortName": "LivestreamService" + }, + "shortName": "CreateDvrSession" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.video.live_stream_v1.types.CreateDvrSessionRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "dvr_session", + "type": "google.cloud.video.live_stream_v1.types.DvrSession" + }, + { + "name": "dvr_session_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "create_dvr_session" + }, + "description": "Sample for CreateDvrSession", + "file": "livestream_v1_generated_livestream_service_create_dvr_session_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "livestream_v1_generated_LivestreamService_CreateDvrSession_sync", + "segments": [ + { + "end": 60, + "start": 27, + "type": "FULL" + }, + { + "end": 60, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 50, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 57, + "start": 51, + "type": "REQUEST_EXECUTION" + }, + { + "end": 61, + "start": 58, + "type": "RESPONSE_HANDLING" + } + ], + "title": "livestream_v1_generated_livestream_service_create_dvr_session_sync.py" + }, { "canonical": true, "clientMethod": { @@ -1387,19 +1564,19 @@ "fullName": "google.cloud.video.live_stream_v1.LivestreamServiceAsyncClient", "shortName": "LivestreamServiceAsyncClient" }, - "fullName": "google.cloud.video.live_stream_v1.LivestreamServiceAsyncClient.delete_event", + "fullName": "google.cloud.video.live_stream_v1.LivestreamServiceAsyncClient.delete_dvr_session", "method": { - "fullName": "google.cloud.video.livestream.v1.LivestreamService.DeleteEvent", + "fullName": "google.cloud.video.livestream.v1.LivestreamService.DeleteDvrSession", "service": { "fullName": "google.cloud.video.livestream.v1.LivestreamService", "shortName": "LivestreamService" }, - "shortName": "DeleteEvent" + "shortName": "DeleteDvrSession" }, "parameters": [ { "name": "request", - "type": "google.cloud.video.live_stream_v1.types.DeleteEventRequest" + "type": "google.cloud.video.live_stream_v1.types.DeleteDvrSessionRequest" }, { "name": "name", @@ -1418,21 +1595,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "shortName": "delete_event" + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "delete_dvr_session" }, - "description": "Sample for DeleteEvent", - "file": "livestream_v1_generated_livestream_service_delete_event_async.py", + "description": "Sample for DeleteDvrSession", + "file": "livestream_v1_generated_livestream_service_delete_dvr_session_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "livestream_v1_generated_LivestreamService_DeleteEvent_async", + "regionTag": "livestream_v1_generated_LivestreamService_DeleteDvrSession_async", "segments": [ { - "end": 49, + "end": 55, "start": 27, "type": "FULL" }, { - "end": 49, + "end": 55, "start": 27, "type": "SHORT" }, @@ -1447,15 +1625,17 @@ "type": "REQUEST_INITIALIZATION" }, { + "end": 52, "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 50, + "end": 56, + "start": 53, "type": "RESPONSE_HANDLING" } ], - "title": "livestream_v1_generated_livestream_service_delete_event_async.py" + "title": "livestream_v1_generated_livestream_service_delete_dvr_session_async.py" }, { "canonical": true, @@ -1464,19 +1644,19 @@ "fullName": "google.cloud.video.live_stream_v1.LivestreamServiceClient", "shortName": "LivestreamServiceClient" }, - "fullName": "google.cloud.video.live_stream_v1.LivestreamServiceClient.delete_event", + "fullName": "google.cloud.video.live_stream_v1.LivestreamServiceClient.delete_dvr_session", "method": { - "fullName": "google.cloud.video.livestream.v1.LivestreamService.DeleteEvent", + "fullName": "google.cloud.video.livestream.v1.LivestreamService.DeleteDvrSession", "service": { "fullName": "google.cloud.video.livestream.v1.LivestreamService", "shortName": "LivestreamService" }, - "shortName": "DeleteEvent" + "shortName": "DeleteDvrSession" }, "parameters": [ { "name": "request", - "type": "google.cloud.video.live_stream_v1.types.DeleteEventRequest" + "type": "google.cloud.video.live_stream_v1.types.DeleteDvrSessionRequest" }, { "name": "name", @@ -1495,21 +1675,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "shortName": "delete_event" + "resultType": "google.api_core.operation.Operation", + "shortName": "delete_dvr_session" }, - "description": "Sample for DeleteEvent", - "file": "livestream_v1_generated_livestream_service_delete_event_sync.py", + "description": "Sample for DeleteDvrSession", + "file": "livestream_v1_generated_livestream_service_delete_dvr_session_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "livestream_v1_generated_LivestreamService_DeleteEvent_sync", + "regionTag": "livestream_v1_generated_LivestreamService_DeleteDvrSession_sync", "segments": [ { - "end": 49, + "end": 55, "start": 27, "type": "FULL" }, { - "end": 49, + "end": 55, "start": 27, "type": "SHORT" }, @@ -1524,15 +1705,17 @@ "type": "REQUEST_INITIALIZATION" }, { + "end": 52, "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 50, + "end": 56, + "start": 53, "type": "RESPONSE_HANDLING" } ], - "title": "livestream_v1_generated_livestream_service_delete_event_sync.py" + "title": "livestream_v1_generated_livestream_service_delete_dvr_session_sync.py" }, { "canonical": true, @@ -1542,19 +1725,19 @@ "fullName": "google.cloud.video.live_stream_v1.LivestreamServiceAsyncClient", "shortName": "LivestreamServiceAsyncClient" }, - "fullName": "google.cloud.video.live_stream_v1.LivestreamServiceAsyncClient.delete_input", + "fullName": "google.cloud.video.live_stream_v1.LivestreamServiceAsyncClient.delete_event", "method": { - "fullName": "google.cloud.video.livestream.v1.LivestreamService.DeleteInput", + "fullName": "google.cloud.video.livestream.v1.LivestreamService.DeleteEvent", "service": { "fullName": "google.cloud.video.livestream.v1.LivestreamService", "shortName": "LivestreamService" }, - "shortName": "DeleteInput" + "shortName": "DeleteEvent" }, "parameters": [ { "name": "request", - "type": "google.cloud.video.live_stream_v1.types.DeleteInputRequest" + "type": "google.cloud.video.live_stream_v1.types.DeleteEventRequest" }, { "name": "name", @@ -1573,22 +1756,21 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "delete_input" + "shortName": "delete_event" }, - "description": "Sample for DeleteInput", - "file": "livestream_v1_generated_livestream_service_delete_input_async.py", + "description": "Sample for DeleteEvent", + "file": "livestream_v1_generated_livestream_service_delete_event_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "livestream_v1_generated_LivestreamService_DeleteInput_async", + "regionTag": "livestream_v1_generated_LivestreamService_DeleteEvent_async", "segments": [ { - "end": 55, + "end": 49, "start": 27, "type": "FULL" }, { - "end": 55, + "end": 49, "start": 27, "type": "SHORT" }, @@ -1603,17 +1785,15 @@ "type": "REQUEST_INITIALIZATION" }, { - "end": 52, "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 56, - "start": 53, + "end": 50, "type": "RESPONSE_HANDLING" } ], - "title": "livestream_v1_generated_livestream_service_delete_input_async.py" + "title": "livestream_v1_generated_livestream_service_delete_event_async.py" }, { "canonical": true, @@ -1622,19 +1802,19 @@ "fullName": "google.cloud.video.live_stream_v1.LivestreamServiceClient", "shortName": "LivestreamServiceClient" }, - "fullName": "google.cloud.video.live_stream_v1.LivestreamServiceClient.delete_input", + "fullName": "google.cloud.video.live_stream_v1.LivestreamServiceClient.delete_event", "method": { - "fullName": "google.cloud.video.livestream.v1.LivestreamService.DeleteInput", + "fullName": "google.cloud.video.livestream.v1.LivestreamService.DeleteEvent", "service": { "fullName": "google.cloud.video.livestream.v1.LivestreamService", "shortName": "LivestreamService" }, - "shortName": "DeleteInput" + "shortName": "DeleteEvent" }, "parameters": [ { "name": "request", - "type": "google.cloud.video.live_stream_v1.types.DeleteInputRequest" + "type": "google.cloud.video.live_stream_v1.types.DeleteEventRequest" }, { "name": "name", @@ -1653,22 +1833,21 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.api_core.operation.Operation", - "shortName": "delete_input" + "shortName": "delete_event" }, - "description": "Sample for DeleteInput", - "file": "livestream_v1_generated_livestream_service_delete_input_sync.py", + "description": "Sample for DeleteEvent", + "file": "livestream_v1_generated_livestream_service_delete_event_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "livestream_v1_generated_LivestreamService_DeleteInput_sync", + "regionTag": "livestream_v1_generated_LivestreamService_DeleteEvent_sync", "segments": [ { - "end": 55, + "end": 49, "start": 27, "type": "FULL" }, { - "end": 55, + "end": 49, "start": 27, "type": "SHORT" }, @@ -1683,17 +1862,15 @@ "type": "REQUEST_INITIALIZATION" }, { - "end": 52, "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 56, - "start": 53, + "end": 50, "type": "RESPONSE_HANDLING" } ], - "title": "livestream_v1_generated_livestream_service_delete_input_sync.py" + "title": "livestream_v1_generated_livestream_service_delete_event_sync.py" }, { "canonical": true, @@ -1703,19 +1880,19 @@ "fullName": "google.cloud.video.live_stream_v1.LivestreamServiceAsyncClient", "shortName": "LivestreamServiceAsyncClient" }, - "fullName": "google.cloud.video.live_stream_v1.LivestreamServiceAsyncClient.get_asset", + "fullName": "google.cloud.video.live_stream_v1.LivestreamServiceAsyncClient.delete_input", "method": { - "fullName": "google.cloud.video.livestream.v1.LivestreamService.GetAsset", + "fullName": "google.cloud.video.livestream.v1.LivestreamService.DeleteInput", "service": { "fullName": "google.cloud.video.livestream.v1.LivestreamService", "shortName": "LivestreamService" }, - "shortName": "GetAsset" + "shortName": "DeleteInput" }, "parameters": [ { "name": "request", - "type": "google.cloud.video.live_stream_v1.types.GetAssetRequest" + "type": "google.cloud.video.live_stream_v1.types.DeleteInputRequest" }, { "name": "name", @@ -1734,10 +1911,171 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.video.live_stream_v1.types.Asset", - "shortName": "get_asset" + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "delete_input" }, - "description": "Sample for GetAsset", + "description": "Sample for DeleteInput", + "file": "livestream_v1_generated_livestream_service_delete_input_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "livestream_v1_generated_LivestreamService_DeleteInput_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": "livestream_v1_generated_livestream_service_delete_input_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.video.live_stream_v1.LivestreamServiceClient", + "shortName": "LivestreamServiceClient" + }, + "fullName": "google.cloud.video.live_stream_v1.LivestreamServiceClient.delete_input", + "method": { + "fullName": "google.cloud.video.livestream.v1.LivestreamService.DeleteInput", + "service": { + "fullName": "google.cloud.video.livestream.v1.LivestreamService", + "shortName": "LivestreamService" + }, + "shortName": "DeleteInput" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.video.live_stream_v1.types.DeleteInputRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "delete_input" + }, + "description": "Sample for DeleteInput", + "file": "livestream_v1_generated_livestream_service_delete_input_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "livestream_v1_generated_LivestreamService_DeleteInput_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": "livestream_v1_generated_livestream_service_delete_input_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.video.live_stream_v1.LivestreamServiceAsyncClient", + "shortName": "LivestreamServiceAsyncClient" + }, + "fullName": "google.cloud.video.live_stream_v1.LivestreamServiceAsyncClient.get_asset", + "method": { + "fullName": "google.cloud.video.livestream.v1.LivestreamService.GetAsset", + "service": { + "fullName": "google.cloud.video.livestream.v1.LivestreamService", + "shortName": "LivestreamService" + }, + "shortName": "GetAsset" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.video.live_stream_v1.types.GetAssetRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.video.live_stream_v1.types.Asset", + "shortName": "get_asset" + }, + "description": "Sample for GetAsset", "file": "livestream_v1_generated_livestream_service_get_asset_async.py", "language": "PYTHON", "origin": "API_DEFINITION", @@ -2178,6 +2516,167 @@ ], "title": "livestream_v1_generated_livestream_service_get_clip_sync.py" }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.video.live_stream_v1.LivestreamServiceAsyncClient", + "shortName": "LivestreamServiceAsyncClient" + }, + "fullName": "google.cloud.video.live_stream_v1.LivestreamServiceAsyncClient.get_dvr_session", + "method": { + "fullName": "google.cloud.video.livestream.v1.LivestreamService.GetDvrSession", + "service": { + "fullName": "google.cloud.video.livestream.v1.LivestreamService", + "shortName": "LivestreamService" + }, + "shortName": "GetDvrSession" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.video.live_stream_v1.types.GetDvrSessionRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.video.live_stream_v1.types.DvrSession", + "shortName": "get_dvr_session" + }, + "description": "Sample for GetDvrSession", + "file": "livestream_v1_generated_livestream_service_get_dvr_session_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "livestream_v1_generated_LivestreamService_GetDvrSession_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": "livestream_v1_generated_livestream_service_get_dvr_session_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.video.live_stream_v1.LivestreamServiceClient", + "shortName": "LivestreamServiceClient" + }, + "fullName": "google.cloud.video.live_stream_v1.LivestreamServiceClient.get_dvr_session", + "method": { + "fullName": "google.cloud.video.livestream.v1.LivestreamService.GetDvrSession", + "service": { + "fullName": "google.cloud.video.livestream.v1.LivestreamService", + "shortName": "LivestreamService" + }, + "shortName": "GetDvrSession" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.video.live_stream_v1.types.GetDvrSessionRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.video.live_stream_v1.types.DvrSession", + "shortName": "get_dvr_session" + }, + "description": "Sample for GetDvrSession", + "file": "livestream_v1_generated_livestream_service_get_dvr_session_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "livestream_v1_generated_LivestreamService_GetDvrSession_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": "livestream_v1_generated_livestream_service_get_dvr_session_sync.py" + }, { "canonical": true, "clientMethod": { @@ -2622,19 +3121,180 @@ "resultType": "google.cloud.video.live_stream_v1.types.Pool", "shortName": "get_pool" }, - "description": "Sample for GetPool", - "file": "livestream_v1_generated_livestream_service_get_pool_sync.py", + "description": "Sample for GetPool", + "file": "livestream_v1_generated_livestream_service_get_pool_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "livestream_v1_generated_LivestreamService_GetPool_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": "livestream_v1_generated_livestream_service_get_pool_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.video.live_stream_v1.LivestreamServiceAsyncClient", + "shortName": "LivestreamServiceAsyncClient" + }, + "fullName": "google.cloud.video.live_stream_v1.LivestreamServiceAsyncClient.list_assets", + "method": { + "fullName": "google.cloud.video.livestream.v1.LivestreamService.ListAssets", + "service": { + "fullName": "google.cloud.video.livestream.v1.LivestreamService", + "shortName": "LivestreamService" + }, + "shortName": "ListAssets" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.video.live_stream_v1.types.ListAssetsRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.video.live_stream_v1.services.livestream_service.pagers.ListAssetsAsyncPager", + "shortName": "list_assets" + }, + "description": "Sample for ListAssets", + "file": "livestream_v1_generated_livestream_service_list_assets_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "livestream_v1_generated_LivestreamService_ListAssets_async", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "livestream_v1_generated_livestream_service_list_assets_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.video.live_stream_v1.LivestreamServiceClient", + "shortName": "LivestreamServiceClient" + }, + "fullName": "google.cloud.video.live_stream_v1.LivestreamServiceClient.list_assets", + "method": { + "fullName": "google.cloud.video.livestream.v1.LivestreamService.ListAssets", + "service": { + "fullName": "google.cloud.video.livestream.v1.LivestreamService", + "shortName": "LivestreamService" + }, + "shortName": "ListAssets" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.video.live_stream_v1.types.ListAssetsRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.video.live_stream_v1.services.livestream_service.pagers.ListAssetsPager", + "shortName": "list_assets" + }, + "description": "Sample for ListAssets", + "file": "livestream_v1_generated_livestream_service_list_assets_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "livestream_v1_generated_LivestreamService_GetPool_sync", + "regionTag": "livestream_v1_generated_LivestreamService_ListAssets_sync", "segments": [ { - "end": 51, + "end": 52, "start": 27, "type": "FULL" }, { - "end": 51, + "end": 52, "start": 27, "type": "SHORT" }, @@ -2654,12 +3314,12 @@ "type": "REQUEST_EXECUTION" }, { - "end": 52, + "end": 53, "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "livestream_v1_generated_livestream_service_get_pool_sync.py" + "title": "livestream_v1_generated_livestream_service_list_assets_sync.py" }, { "canonical": true, @@ -2669,19 +3329,19 @@ "fullName": "google.cloud.video.live_stream_v1.LivestreamServiceAsyncClient", "shortName": "LivestreamServiceAsyncClient" }, - "fullName": "google.cloud.video.live_stream_v1.LivestreamServiceAsyncClient.list_assets", + "fullName": "google.cloud.video.live_stream_v1.LivestreamServiceAsyncClient.list_channels", "method": { - "fullName": "google.cloud.video.livestream.v1.LivestreamService.ListAssets", + "fullName": "google.cloud.video.livestream.v1.LivestreamService.ListChannels", "service": { "fullName": "google.cloud.video.livestream.v1.LivestreamService", "shortName": "LivestreamService" }, - "shortName": "ListAssets" + "shortName": "ListChannels" }, "parameters": [ { "name": "request", - "type": "google.cloud.video.live_stream_v1.types.ListAssetsRequest" + "type": "google.cloud.video.live_stream_v1.types.ListChannelsRequest" }, { "name": "parent", @@ -2700,14 +3360,14 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.video.live_stream_v1.services.livestream_service.pagers.ListAssetsAsyncPager", - "shortName": "list_assets" + "resultType": "google.cloud.video.live_stream_v1.services.livestream_service.pagers.ListChannelsAsyncPager", + "shortName": "list_channels" }, - "description": "Sample for ListAssets", - "file": "livestream_v1_generated_livestream_service_list_assets_async.py", + "description": "Sample for ListChannels", + "file": "livestream_v1_generated_livestream_service_list_channels_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "livestream_v1_generated_LivestreamService_ListAssets_async", + "regionTag": "livestream_v1_generated_LivestreamService_ListChannels_async", "segments": [ { "end": 52, @@ -2740,7 +3400,7 @@ "type": "RESPONSE_HANDLING" } ], - "title": "livestream_v1_generated_livestream_service_list_assets_async.py" + "title": "livestream_v1_generated_livestream_service_list_channels_async.py" }, { "canonical": true, @@ -2749,19 +3409,19 @@ "fullName": "google.cloud.video.live_stream_v1.LivestreamServiceClient", "shortName": "LivestreamServiceClient" }, - "fullName": "google.cloud.video.live_stream_v1.LivestreamServiceClient.list_assets", + "fullName": "google.cloud.video.live_stream_v1.LivestreamServiceClient.list_channels", "method": { - "fullName": "google.cloud.video.livestream.v1.LivestreamService.ListAssets", + "fullName": "google.cloud.video.livestream.v1.LivestreamService.ListChannels", "service": { "fullName": "google.cloud.video.livestream.v1.LivestreamService", "shortName": "LivestreamService" }, - "shortName": "ListAssets" + "shortName": "ListChannels" }, "parameters": [ { "name": "request", - "type": "google.cloud.video.live_stream_v1.types.ListAssetsRequest" + "type": "google.cloud.video.live_stream_v1.types.ListChannelsRequest" }, { "name": "parent", @@ -2780,14 +3440,14 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.video.live_stream_v1.services.livestream_service.pagers.ListAssetsPager", - "shortName": "list_assets" + "resultType": "google.cloud.video.live_stream_v1.services.livestream_service.pagers.ListChannelsPager", + "shortName": "list_channels" }, - "description": "Sample for ListAssets", - "file": "livestream_v1_generated_livestream_service_list_assets_sync.py", + "description": "Sample for ListChannels", + "file": "livestream_v1_generated_livestream_service_list_channels_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "livestream_v1_generated_LivestreamService_ListAssets_sync", + "regionTag": "livestream_v1_generated_LivestreamService_ListChannels_sync", "segments": [ { "end": 52, @@ -2820,7 +3480,7 @@ "type": "RESPONSE_HANDLING" } ], - "title": "livestream_v1_generated_livestream_service_list_assets_sync.py" + "title": "livestream_v1_generated_livestream_service_list_channels_sync.py" }, { "canonical": true, @@ -2830,19 +3490,19 @@ "fullName": "google.cloud.video.live_stream_v1.LivestreamServiceAsyncClient", "shortName": "LivestreamServiceAsyncClient" }, - "fullName": "google.cloud.video.live_stream_v1.LivestreamServiceAsyncClient.list_channels", + "fullName": "google.cloud.video.live_stream_v1.LivestreamServiceAsyncClient.list_clips", "method": { - "fullName": "google.cloud.video.livestream.v1.LivestreamService.ListChannels", + "fullName": "google.cloud.video.livestream.v1.LivestreamService.ListClips", "service": { "fullName": "google.cloud.video.livestream.v1.LivestreamService", "shortName": "LivestreamService" }, - "shortName": "ListChannels" + "shortName": "ListClips" }, "parameters": [ { "name": "request", - "type": "google.cloud.video.live_stream_v1.types.ListChannelsRequest" + "type": "google.cloud.video.live_stream_v1.types.ListClipsRequest" }, { "name": "parent", @@ -2861,14 +3521,14 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.video.live_stream_v1.services.livestream_service.pagers.ListChannelsAsyncPager", - "shortName": "list_channels" + "resultType": "google.cloud.video.live_stream_v1.services.livestream_service.pagers.ListClipsAsyncPager", + "shortName": "list_clips" }, - "description": "Sample for ListChannels", - "file": "livestream_v1_generated_livestream_service_list_channels_async.py", + "description": "Sample for ListClips", + "file": "livestream_v1_generated_livestream_service_list_clips_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "livestream_v1_generated_LivestreamService_ListChannels_async", + "regionTag": "livestream_v1_generated_LivestreamService_ListClips_async", "segments": [ { "end": 52, @@ -2901,7 +3561,7 @@ "type": "RESPONSE_HANDLING" } ], - "title": "livestream_v1_generated_livestream_service_list_channels_async.py" + "title": "livestream_v1_generated_livestream_service_list_clips_async.py" }, { "canonical": true, @@ -2910,19 +3570,19 @@ "fullName": "google.cloud.video.live_stream_v1.LivestreamServiceClient", "shortName": "LivestreamServiceClient" }, - "fullName": "google.cloud.video.live_stream_v1.LivestreamServiceClient.list_channels", + "fullName": "google.cloud.video.live_stream_v1.LivestreamServiceClient.list_clips", "method": { - "fullName": "google.cloud.video.livestream.v1.LivestreamService.ListChannels", + "fullName": "google.cloud.video.livestream.v1.LivestreamService.ListClips", "service": { "fullName": "google.cloud.video.livestream.v1.LivestreamService", "shortName": "LivestreamService" }, - "shortName": "ListChannels" + "shortName": "ListClips" }, "parameters": [ { "name": "request", - "type": "google.cloud.video.live_stream_v1.types.ListChannelsRequest" + "type": "google.cloud.video.live_stream_v1.types.ListClipsRequest" }, { "name": "parent", @@ -2941,14 +3601,14 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.video.live_stream_v1.services.livestream_service.pagers.ListChannelsPager", - "shortName": "list_channels" + "resultType": "google.cloud.video.live_stream_v1.services.livestream_service.pagers.ListClipsPager", + "shortName": "list_clips" }, - "description": "Sample for ListChannels", - "file": "livestream_v1_generated_livestream_service_list_channels_sync.py", + "description": "Sample for ListClips", + "file": "livestream_v1_generated_livestream_service_list_clips_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "livestream_v1_generated_LivestreamService_ListChannels_sync", + "regionTag": "livestream_v1_generated_LivestreamService_ListClips_sync", "segments": [ { "end": 52, @@ -2981,7 +3641,7 @@ "type": "RESPONSE_HANDLING" } ], - "title": "livestream_v1_generated_livestream_service_list_channels_sync.py" + "title": "livestream_v1_generated_livestream_service_list_clips_sync.py" }, { "canonical": true, @@ -2991,19 +3651,19 @@ "fullName": "google.cloud.video.live_stream_v1.LivestreamServiceAsyncClient", "shortName": "LivestreamServiceAsyncClient" }, - "fullName": "google.cloud.video.live_stream_v1.LivestreamServiceAsyncClient.list_clips", + "fullName": "google.cloud.video.live_stream_v1.LivestreamServiceAsyncClient.list_dvr_sessions", "method": { - "fullName": "google.cloud.video.livestream.v1.LivestreamService.ListClips", + "fullName": "google.cloud.video.livestream.v1.LivestreamService.ListDvrSessions", "service": { "fullName": "google.cloud.video.livestream.v1.LivestreamService", "shortName": "LivestreamService" }, - "shortName": "ListClips" + "shortName": "ListDvrSessions" }, "parameters": [ { "name": "request", - "type": "google.cloud.video.live_stream_v1.types.ListClipsRequest" + "type": "google.cloud.video.live_stream_v1.types.ListDvrSessionsRequest" }, { "name": "parent", @@ -3022,14 +3682,14 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.video.live_stream_v1.services.livestream_service.pagers.ListClipsAsyncPager", - "shortName": "list_clips" + "resultType": "google.cloud.video.live_stream_v1.services.livestream_service.pagers.ListDvrSessionsAsyncPager", + "shortName": "list_dvr_sessions" }, - "description": "Sample for ListClips", - "file": "livestream_v1_generated_livestream_service_list_clips_async.py", + "description": "Sample for ListDvrSessions", + "file": "livestream_v1_generated_livestream_service_list_dvr_sessions_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "livestream_v1_generated_LivestreamService_ListClips_async", + "regionTag": "livestream_v1_generated_LivestreamService_ListDvrSessions_async", "segments": [ { "end": 52, @@ -3062,7 +3722,7 @@ "type": "RESPONSE_HANDLING" } ], - "title": "livestream_v1_generated_livestream_service_list_clips_async.py" + "title": "livestream_v1_generated_livestream_service_list_dvr_sessions_async.py" }, { "canonical": true, @@ -3071,19 +3731,19 @@ "fullName": "google.cloud.video.live_stream_v1.LivestreamServiceClient", "shortName": "LivestreamServiceClient" }, - "fullName": "google.cloud.video.live_stream_v1.LivestreamServiceClient.list_clips", + "fullName": "google.cloud.video.live_stream_v1.LivestreamServiceClient.list_dvr_sessions", "method": { - "fullName": "google.cloud.video.livestream.v1.LivestreamService.ListClips", + "fullName": "google.cloud.video.livestream.v1.LivestreamService.ListDvrSessions", "service": { "fullName": "google.cloud.video.livestream.v1.LivestreamService", "shortName": "LivestreamService" }, - "shortName": "ListClips" + "shortName": "ListDvrSessions" }, "parameters": [ { "name": "request", - "type": "google.cloud.video.live_stream_v1.types.ListClipsRequest" + "type": "google.cloud.video.live_stream_v1.types.ListDvrSessionsRequest" }, { "name": "parent", @@ -3102,14 +3762,14 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.video.live_stream_v1.services.livestream_service.pagers.ListClipsPager", - "shortName": "list_clips" + "resultType": "google.cloud.video.live_stream_v1.services.livestream_service.pagers.ListDvrSessionsPager", + "shortName": "list_dvr_sessions" }, - "description": "Sample for ListClips", - "file": "livestream_v1_generated_livestream_service_list_clips_sync.py", + "description": "Sample for ListDvrSessions", + "file": "livestream_v1_generated_livestream_service_list_dvr_sessions_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "livestream_v1_generated_LivestreamService_ListClips_sync", + "regionTag": "livestream_v1_generated_LivestreamService_ListDvrSessions_sync", "segments": [ { "end": 52, @@ -3142,7 +3802,7 @@ "type": "RESPONSE_HANDLING" } ], - "title": "livestream_v1_generated_livestream_service_list_clips_sync.py" + "title": "livestream_v1_generated_livestream_service_list_dvr_sessions_sync.py" }, { "canonical": true, @@ -3957,6 +4617,175 @@ ], "title": "livestream_v1_generated_livestream_service_update_channel_sync.py" }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.video.live_stream_v1.LivestreamServiceAsyncClient", + "shortName": "LivestreamServiceAsyncClient" + }, + "fullName": "google.cloud.video.live_stream_v1.LivestreamServiceAsyncClient.update_dvr_session", + "method": { + "fullName": "google.cloud.video.livestream.v1.LivestreamService.UpdateDvrSession", + "service": { + "fullName": "google.cloud.video.livestream.v1.LivestreamService", + "shortName": "LivestreamService" + }, + "shortName": "UpdateDvrSession" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.video.live_stream_v1.types.UpdateDvrSessionRequest" + }, + { + "name": "dvr_session", + "type": "google.cloud.video.live_stream_v1.types.DvrSession" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "update_dvr_session" + }, + "description": "Sample for UpdateDvrSession", + "file": "livestream_v1_generated_livestream_service_update_dvr_session_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "livestream_v1_generated_LivestreamService_UpdateDvrSession_async", + "segments": [ + { + "end": 58, + "start": 27, + "type": "FULL" + }, + { + "end": 58, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 48, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 55, + "start": 49, + "type": "REQUEST_EXECUTION" + }, + { + "end": 59, + "start": 56, + "type": "RESPONSE_HANDLING" + } + ], + "title": "livestream_v1_generated_livestream_service_update_dvr_session_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.video.live_stream_v1.LivestreamServiceClient", + "shortName": "LivestreamServiceClient" + }, + "fullName": "google.cloud.video.live_stream_v1.LivestreamServiceClient.update_dvr_session", + "method": { + "fullName": "google.cloud.video.livestream.v1.LivestreamService.UpdateDvrSession", + "service": { + "fullName": "google.cloud.video.livestream.v1.LivestreamService", + "shortName": "LivestreamService" + }, + "shortName": "UpdateDvrSession" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.video.live_stream_v1.types.UpdateDvrSessionRequest" + }, + { + "name": "dvr_session", + "type": "google.cloud.video.live_stream_v1.types.DvrSession" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "update_dvr_session" + }, + "description": "Sample for UpdateDvrSession", + "file": "livestream_v1_generated_livestream_service_update_dvr_session_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "livestream_v1_generated_LivestreamService_UpdateDvrSession_sync", + "segments": [ + { + "end": 58, + "start": 27, + "type": "FULL" + }, + { + "end": 58, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 48, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 55, + "start": 49, + "type": "REQUEST_EXECUTION" + }, + { + "end": 59, + "start": 56, + "type": "RESPONSE_HANDLING" + } + ], + "title": "livestream_v1_generated_livestream_service_update_dvr_session_sync.py" + }, { "canonical": true, "clientMethod": { diff --git a/packages/google-cloud-video-live-stream/scripts/fixup_live_stream_v1_keywords.py b/packages/google-cloud-video-live-stream/scripts/fixup_live_stream_v1_keywords.py index 26403d02dabf..19f860999c3a 100644 --- a/packages/google-cloud-video-live-stream/scripts/fixup_live_stream_v1_keywords.py +++ b/packages/google-cloud-video-live-stream/scripts/fixup_live_stream_v1_keywords.py @@ -42,27 +42,32 @@ class live_streamCallTransformer(cst.CSTTransformer): 'create_asset': ('parent', 'asset', 'asset_id', 'request_id', ), 'create_channel': ('parent', 'channel', 'channel_id', 'request_id', ), 'create_clip': ('parent', 'clip_id', 'clip', 'request_id', ), + 'create_dvr_session': ('parent', 'dvr_session_id', 'dvr_session', 'request_id', ), 'create_event': ('parent', 'event', 'event_id', 'request_id', ), 'create_input': ('parent', 'input', 'input_id', 'request_id', ), 'delete_asset': ('name', 'request_id', ), 'delete_channel': ('name', 'request_id', 'force', ), 'delete_clip': ('name', 'request_id', ), + 'delete_dvr_session': ('name', 'request_id', ), 'delete_event': ('name', 'request_id', ), 'delete_input': ('name', 'request_id', ), 'get_asset': ('name', ), 'get_channel': ('name', ), 'get_clip': ('name', ), + 'get_dvr_session': ('name', ), 'get_event': ('name', ), 'get_input': ('name', ), 'get_pool': ('name', ), 'list_assets': ('parent', 'page_size', 'page_token', 'filter', 'order_by', ), 'list_channels': ('parent', 'page_size', 'page_token', 'filter', 'order_by', ), 'list_clips': ('parent', 'page_size', 'page_token', 'filter', 'order_by', ), + 'list_dvr_sessions': ('parent', 'page_size', 'page_token', 'filter', 'order_by', ), 'list_events': ('parent', 'page_size', 'page_token', 'filter', 'order_by', ), 'list_inputs': ('parent', 'page_size', 'page_token', 'filter', 'order_by', ), 'start_channel': ('name', 'request_id', ), 'stop_channel': ('name', 'request_id', ), 'update_channel': ('channel', 'update_mask', 'request_id', ), + 'update_dvr_session': ('update_mask', 'dvr_session', 'request_id', ), 'update_input': ('input', 'update_mask', 'request_id', ), 'update_pool': ('pool', 'update_mask', 'request_id', ), } diff --git a/packages/google-cloud-video-live-stream/tests/unit/gapic/live_stream_v1/test_livestream_service.py b/packages/google-cloud-video-live-stream/tests/unit/gapic/live_stream_v1/test_livestream_service.py index 1e7e70f18c4f..98a7ea4d6826 100644 --- a/packages/google-cloud-video-live-stream/tests/unit/gapic/live_stream_v1/test_livestream_service.py +++ b/packages/google-cloud-video-live-stream/tests/unit/gapic/live_stream_v1/test_livestream_service.py @@ -7633,6 +7633,7 @@ def test_get_clip(request_type, transport: str = "grpc"): name="name_value", state=resources.Clip.State.PENDING, output_uri="output_uri_value", + output_type=resources.Clip.OutputType.MANIFEST, ) response = client.get_clip(request) @@ -7647,6 +7648,7 @@ def test_get_clip(request_type, transport: str = "grpc"): assert response.name == "name_value" assert response.state == resources.Clip.State.PENDING assert response.output_uri == "output_uri_value" + assert response.output_type == resources.Clip.OutputType.MANIFEST def test_get_clip_non_empty_request_with_auto_populated_field(): @@ -7773,6 +7775,7 @@ async def test_get_clip_async( name="name_value", state=resources.Clip.State.PENDING, output_uri="output_uri_value", + output_type=resources.Clip.OutputType.MANIFEST, ) ) response = await client.get_clip(request) @@ -7788,6 +7791,7 @@ async def test_get_clip_async( assert response.name == "name_value" assert response.state == resources.Clip.State.PENDING assert response.output_uri == "output_uri_value" + assert response.output_type == resources.Clip.OutputType.MANIFEST @pytest.mark.asyncio @@ -8615,11 +8619,11 @@ async def test_delete_clip_flattened_error_async(): @pytest.mark.parametrize( "request_type", [ - service.CreateAssetRequest, + service.CreateDvrSessionRequest, dict, ], ) -def test_create_asset(request_type, transport: str = "grpc"): +def test_create_dvr_session(request_type, transport: str = "grpc"): client = LivestreamServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -8630,22 +8634,24 @@ def test_create_asset(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_asset), "__call__") as call: + with mock.patch.object( + type(client.transport.create_dvr_session), "__call__" + ) as call: # Designate an appropriate return value for the call. call.return_value = operations_pb2.Operation(name="operations/spam") - response = client.create_asset(request) + response = client.create_dvr_session(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - request = service.CreateAssetRequest() + request = service.CreateDvrSessionRequest() assert args[0] == request # Establish that the response is the type that we expect. assert isinstance(response, future.Future) -def test_create_asset_non_empty_request_with_auto_populated_field(): +def test_create_dvr_session_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. client = LivestreamServiceClient( @@ -8656,28 +8662,28 @@ def test_create_asset_non_empty_request_with_auto_populated_field(): # Populate all string fields in the request which are not UUID4 # since we want to check that UUID4 are populated automatically # if they meet the requirements of AIP 4235. - request = service.CreateAssetRequest( + request = service.CreateDvrSessionRequest( parent="parent_value", - asset_id="asset_id_value", - request_id="request_id_value", + dvr_session_id="dvr_session_id_value", ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.create_asset), "__call__") as call: + with mock.patch.object( + type(client.transport.create_dvr_session), "__call__" + ) as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.create_asset(request=request) + client.create_dvr_session(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == service.CreateAssetRequest( + assert args[0] == service.CreateDvrSessionRequest( parent="parent_value", - asset_id="asset_id_value", - request_id="request_id_value", + dvr_session_id="dvr_session_id_value", ) -def test_create_asset_use_cached_wrapped_rpc(): +def test_create_dvr_session_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -8691,16 +8697,20 @@ def test_create_asset_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.create_asset in client._transport._wrapped_methods + assert ( + client._transport.create_dvr_session in client._transport._wrapped_methods + ) # Replace cached wrapped function with mock mock_rpc = 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_asset] = mock_rpc + client._transport._wrapped_methods[ + client._transport.create_dvr_session + ] = mock_rpc request = {} - client.create_asset(request) + client.create_dvr_session(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 @@ -8710,7 +8720,7 @@ def test_create_asset_use_cached_wrapped_rpc(): # Subsequent calls should use the cached wrapper wrapper_fn.reset_mock() - client.create_asset(request) + client.create_dvr_session(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -8718,7 +8728,7 @@ def test_create_asset_use_cached_wrapped_rpc(): @pytest.mark.asyncio -async def test_create_asset_async_use_cached_wrapped_rpc( +async def test_create_dvr_session_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", ): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, @@ -8735,7 +8745,7 @@ async def test_create_asset_async_use_cached_wrapped_rpc( # Ensure method has been cached assert ( - client._client._transport.create_asset + client._client._transport.create_dvr_session in client._client._transport._wrapped_methods ) @@ -8743,11 +8753,11 @@ async def test_create_asset_async_use_cached_wrapped_rpc( mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() client._client._transport._wrapped_methods[ - client._client._transport.create_asset + client._client._transport.create_dvr_session ] = mock_rpc request = {} - await client.create_asset(request) + await client.create_dvr_session(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 @@ -8757,7 +8767,7 @@ async def test_create_asset_async_use_cached_wrapped_rpc( # Subsequent calls should use the cached wrapper wrapper_fn.reset_mock() - await client.create_asset(request) + await client.create_dvr_session(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -8765,8 +8775,8 @@ async def test_create_asset_async_use_cached_wrapped_rpc( @pytest.mark.asyncio -async def test_create_asset_async( - transport: str = "grpc_asyncio", request_type=service.CreateAssetRequest +async def test_create_dvr_session_async( + transport: str = "grpc_asyncio", request_type=service.CreateDvrSessionRequest ): client = LivestreamServiceAsyncClient( credentials=async_anonymous_credentials(), @@ -8778,17 +8788,19 @@ async def test_create_asset_async( request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.create_asset), "__call__") as call: + with mock.patch.object( + type(client.transport.create_dvr_session), "__call__" + ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( operations_pb2.Operation(name="operations/spam") ) - response = await client.create_asset(request) + response = await client.create_dvr_session(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request = service.CreateAssetRequest() + request = service.CreateDvrSessionRequest() assert args[0] == request # Establish that the response is the type that we expect. @@ -8796,25 +8808,27 @@ async def test_create_asset_async( @pytest.mark.asyncio -async def test_create_asset_async_from_dict(): - await test_create_asset_async(request_type=dict) +async def test_create_dvr_session_async_from_dict(): + await test_create_dvr_session_async(request_type=dict) -def test_create_asset_field_headers(): +def test_create_dvr_session_field_headers(): client = LivestreamServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = service.CreateAssetRequest() + request = service.CreateDvrSessionRequest() request.parent = "parent_value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.create_asset), "__call__") as call: + with mock.patch.object( + type(client.transport.create_dvr_session), "__call__" + ) as call: call.return_value = operations_pb2.Operation(name="operations/op") - client.create_asset(request) + client.create_dvr_session(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 @@ -8830,23 +8844,25 @@ def test_create_asset_field_headers(): @pytest.mark.asyncio -async def test_create_asset_field_headers_async(): +async def test_create_dvr_session_field_headers_async(): client = LivestreamServiceAsyncClient( credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = service.CreateAssetRequest() + request = service.CreateDvrSessionRequest() request.parent = "parent_value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.create_asset), "__call__") as call: + with mock.patch.object( + type(client.transport.create_dvr_session), "__call__" + ) as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( operations_pb2.Operation(name="operations/op") ) - await client.create_asset(request) + await client.create_dvr_session(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) @@ -8861,21 +8877,23 @@ async def test_create_asset_field_headers_async(): ) in kw["metadata"] -def test_create_asset_flattened(): +def test_create_dvr_session_flattened(): client = LivestreamServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.create_asset), "__call__") as call: + with mock.patch.object( + type(client.transport.create_dvr_session), "__call__" + ) as call: # Designate an appropriate return value for the call. call.return_value = operations_pb2.Operation(name="operations/op") # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - client.create_asset( + client.create_dvr_session( parent="parent_value", - asset=resources.Asset(name="name_value"), - asset_id="asset_id_value", + dvr_session=resources.DvrSession(name="name_value"), + dvr_session_id="dvr_session_id_value", ) # Establish that the underlying call was made with the expected @@ -8885,15 +8903,15 @@ def test_create_asset_flattened(): arg = args[0].parent mock_val = "parent_value" assert arg == mock_val - arg = args[0].asset - mock_val = resources.Asset(name="name_value") + arg = args[0].dvr_session + mock_val = resources.DvrSession(name="name_value") assert arg == mock_val - arg = args[0].asset_id - mock_val = "asset_id_value" + arg = args[0].dvr_session_id + mock_val = "dvr_session_id_value" assert arg == mock_val -def test_create_asset_flattened_error(): +def test_create_dvr_session_flattened_error(): client = LivestreamServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -8901,22 +8919,24 @@ def test_create_asset_flattened_error(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.create_asset( - service.CreateAssetRequest(), + client.create_dvr_session( + service.CreateDvrSessionRequest(), parent="parent_value", - asset=resources.Asset(name="name_value"), - asset_id="asset_id_value", + dvr_session=resources.DvrSession(name="name_value"), + dvr_session_id="dvr_session_id_value", ) @pytest.mark.asyncio -async def test_create_asset_flattened_async(): +async def test_create_dvr_session_flattened_async(): client = LivestreamServiceAsyncClient( credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.create_asset), "__call__") as call: + with mock.patch.object( + type(client.transport.create_dvr_session), "__call__" + ) as call: # Designate an appropriate return value for the call. call.return_value = operations_pb2.Operation(name="operations/op") @@ -8925,10 +8945,10 @@ async def test_create_asset_flattened_async(): ) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - response = await client.create_asset( + response = await client.create_dvr_session( parent="parent_value", - asset=resources.Asset(name="name_value"), - asset_id="asset_id_value", + dvr_session=resources.DvrSession(name="name_value"), + dvr_session_id="dvr_session_id_value", ) # Establish that the underlying call was made with the expected @@ -8938,16 +8958,16 @@ async def test_create_asset_flattened_async(): arg = args[0].parent mock_val = "parent_value" assert arg == mock_val - arg = args[0].asset - mock_val = resources.Asset(name="name_value") + arg = args[0].dvr_session + mock_val = resources.DvrSession(name="name_value") assert arg == mock_val - arg = args[0].asset_id - mock_val = "asset_id_value" + arg = args[0].dvr_session_id + mock_val = "dvr_session_id_value" assert arg == mock_val @pytest.mark.asyncio -async def test_create_asset_flattened_error_async(): +async def test_create_dvr_session_flattened_error_async(): client = LivestreamServiceAsyncClient( credentials=async_anonymous_credentials(), ) @@ -8955,22 +8975,22 @@ async def test_create_asset_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_asset( - service.CreateAssetRequest(), + await client.create_dvr_session( + service.CreateDvrSessionRequest(), parent="parent_value", - asset=resources.Asset(name="name_value"), - asset_id="asset_id_value", + dvr_session=resources.DvrSession(name="name_value"), + dvr_session_id="dvr_session_id_value", ) @pytest.mark.parametrize( "request_type", [ - service.DeleteAssetRequest, + service.ListDvrSessionsRequest, dict, ], ) -def test_delete_asset(request_type, transport: str = "grpc"): +def test_list_dvr_sessions(request_type, transport: str = "grpc"): client = LivestreamServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -8981,22 +9001,29 @@ def test_delete_asset(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_asset), "__call__") as call: + with mock.patch.object( + type(client.transport.list_dvr_sessions), "__call__" + ) as call: # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name="operations/spam") - response = client.delete_asset(request) + call.return_value = service.ListDvrSessionsResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], + ) + response = client.list_dvr_sessions(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - request = service.DeleteAssetRequest() + request = service.ListDvrSessionsRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) + assert isinstance(response, pagers.ListDvrSessionsPager) + assert response.next_page_token == "next_page_token_value" + assert response.unreachable == ["unreachable_value"] -def test_delete_asset_non_empty_request_with_auto_populated_field(): +def test_list_dvr_sessions_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. client = LivestreamServiceClient( @@ -9007,26 +9034,32 @@ def test_delete_asset_non_empty_request_with_auto_populated_field(): # Populate all string fields in the request which are not UUID4 # since we want to check that UUID4 are populated automatically # if they meet the requirements of AIP 4235. - request = service.DeleteAssetRequest( - name="name_value", - request_id="request_id_value", + request = service.ListDvrSessionsRequest( + parent="parent_value", + page_token="page_token_value", + filter="filter_value", + order_by="order_by_value", ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.delete_asset), "__call__") as call: + with mock.patch.object( + type(client.transport.list_dvr_sessions), "__call__" + ) as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.delete_asset(request=request) + client.list_dvr_sessions(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == service.DeleteAssetRequest( - name="name_value", - request_id="request_id_value", + assert args[0] == service.ListDvrSessionsRequest( + parent="parent_value", + page_token="page_token_value", + filter="filter_value", + order_by="order_by_value", ) -def test_delete_asset_use_cached_wrapped_rpc(): +def test_list_dvr_sessions_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -9040,26 +9073,23 @@ def test_delete_asset_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.delete_asset in client._transport._wrapped_methods + assert client._transport.list_dvr_sessions in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = 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_asset] = mock_rpc + client._transport._wrapped_methods[ + client._transport.list_dvr_sessions + ] = mock_rpc request = {} - client.delete_asset(request) + client.list_dvr_sessions(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - # Operation methods call wrapper_fn to build a cached - # client._transport.operations_client instance on first rpc call. - # Subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() - - client.delete_asset(request) + client.list_dvr_sessions(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -9067,7 +9097,7 @@ def test_delete_asset_use_cached_wrapped_rpc(): @pytest.mark.asyncio -async def test_delete_asset_async_use_cached_wrapped_rpc( +async def test_list_dvr_sessions_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", ): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, @@ -9084,7 +9114,7 @@ async def test_delete_asset_async_use_cached_wrapped_rpc( # Ensure method has been cached assert ( - client._client._transport.delete_asset + client._client._transport.list_dvr_sessions in client._client._transport._wrapped_methods ) @@ -9092,21 +9122,16 @@ async def test_delete_asset_async_use_cached_wrapped_rpc( mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() client._client._transport._wrapped_methods[ - client._client._transport.delete_asset + client._client._transport.list_dvr_sessions ] = mock_rpc request = {} - await client.delete_asset(request) + await client.list_dvr_sessions(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - # Operation methods call wrapper_fn to build a cached - # client._transport.operations_client instance on first rpc call. - # Subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() - - await client.delete_asset(request) + await client.list_dvr_sessions(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -9114,8 +9139,8 @@ async def test_delete_asset_async_use_cached_wrapped_rpc( @pytest.mark.asyncio -async def test_delete_asset_async( - transport: str = "grpc_asyncio", request_type=service.DeleteAssetRequest +async def test_list_dvr_sessions_async( + transport: str = "grpc_asyncio", request_type=service.ListDvrSessionsRequest ): client = LivestreamServiceAsyncClient( credentials=async_anonymous_credentials(), @@ -9127,43 +9152,52 @@ async def test_delete_asset_async( request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.delete_asset), "__call__") as call: + with mock.patch.object( + type(client.transport.list_dvr_sessions), "__call__" + ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") + service.ListDvrSessionsResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], + ) ) - response = await client.delete_asset(request) + response = await client.list_dvr_sessions(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request = service.DeleteAssetRequest() + request = service.ListDvrSessionsRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) + assert isinstance(response, pagers.ListDvrSessionsAsyncPager) + assert response.next_page_token == "next_page_token_value" + assert response.unreachable == ["unreachable_value"] @pytest.mark.asyncio -async def test_delete_asset_async_from_dict(): - await test_delete_asset_async(request_type=dict) +async def test_list_dvr_sessions_async_from_dict(): + await test_list_dvr_sessions_async(request_type=dict) -def test_delete_asset_field_headers(): +def test_list_dvr_sessions_field_headers(): client = LivestreamServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = service.DeleteAssetRequest() + request = service.ListDvrSessionsRequest() - request.name = "name_value" + request.parent = "parent_value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.delete_asset), "__call__") as call: - call.return_value = operations_pb2.Operation(name="operations/op") - client.delete_asset(request) + with mock.patch.object( + type(client.transport.list_dvr_sessions), "__call__" + ) as call: + call.return_value = service.ListDvrSessionsResponse() + client.list_dvr_sessions(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 @@ -9174,28 +9208,30 @@ def test_delete_asset_field_headers(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "name=name_value", + "parent=parent_value", ) in kw["metadata"] @pytest.mark.asyncio -async def test_delete_asset_field_headers_async(): +async def test_list_dvr_sessions_field_headers_async(): client = LivestreamServiceAsyncClient( credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = service.DeleteAssetRequest() + request = service.ListDvrSessionsRequest() - request.name = "name_value" + request.parent = "parent_value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.delete_asset), "__call__") as call: + with mock.patch.object( + type(client.transport.list_dvr_sessions), "__call__" + ) as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/op") + service.ListDvrSessionsResponse() ) - await client.delete_asset(request) + await client.list_dvr_sessions(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) @@ -9206,35 +9242,37 @@ async def test_delete_asset_field_headers_async(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "name=name_value", + "parent=parent_value", ) in kw["metadata"] -def test_delete_asset_flattened(): +def test_list_dvr_sessions_flattened(): client = LivestreamServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.delete_asset), "__call__") as call: + with mock.patch.object( + type(client.transport.list_dvr_sessions), "__call__" + ) as call: # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name="operations/op") + call.return_value = service.ListDvrSessionsResponse() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - client.delete_asset( - name="name_value", + client.list_dvr_sessions( + parent="parent_value", ) # Establish that the underlying call was made with the expected # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = "name_value" + arg = args[0].parent + mock_val = "parent_value" assert arg == mock_val -def test_delete_asset_flattened_error(): +def test_list_dvr_sessions_flattened_error(): client = LivestreamServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -9242,43 +9280,45 @@ def test_delete_asset_flattened_error(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.delete_asset( - service.DeleteAssetRequest(), - name="name_value", + client.list_dvr_sessions( + service.ListDvrSessionsRequest(), + parent="parent_value", ) @pytest.mark.asyncio -async def test_delete_asset_flattened_async(): +async def test_list_dvr_sessions_flattened_async(): client = LivestreamServiceAsyncClient( credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.delete_asset), "__call__") as call: + with mock.patch.object( + type(client.transport.list_dvr_sessions), "__call__" + ) as call: # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name="operations/op") + call.return_value = service.ListDvrSessionsResponse() call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") + service.ListDvrSessionsResponse() ) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - response = await client.delete_asset( - name="name_value", + response = await client.list_dvr_sessions( + parent="parent_value", ) # Establish that the underlying call was made with the expected # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = "name_value" + arg = args[0].parent + mock_val = "parent_value" assert arg == mock_val @pytest.mark.asyncio -async def test_delete_asset_flattened_error_async(): +async def test_list_dvr_sessions_flattened_error_async(): client = LivestreamServiceAsyncClient( credentials=async_anonymous_credentials(), ) @@ -9286,53 +9326,253 @@ async def test_delete_asset_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_asset( - service.DeleteAssetRequest(), - name="name_value", + await client.list_dvr_sessions( + service.ListDvrSessionsRequest(), + parent="parent_value", ) -@pytest.mark.parametrize( - "request_type", - [ - service.GetAssetRequest, - dict, - ], -) -def test_get_asset(request_type, transport: str = "grpc"): +def test_list_dvr_sessions_pager(transport_name: str = "grpc"): client = LivestreamServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport=transport, + transport=transport_name, ) - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_asset), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = resources.Asset( - name="name_value", - crc32c="crc32c_value", - state=resources.Asset.State.CREATING, + with mock.patch.object( + type(client.transport.list_dvr_sessions), "__call__" + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + service.ListDvrSessionsResponse( + dvr_sessions=[ + resources.DvrSession(), + resources.DvrSession(), + resources.DvrSession(), + ], + next_page_token="abc", + ), + service.ListDvrSessionsResponse( + dvr_sessions=[], + next_page_token="def", + ), + service.ListDvrSessionsResponse( + dvr_sessions=[ + resources.DvrSession(), + ], + next_page_token="ghi", + ), + service.ListDvrSessionsResponse( + dvr_sessions=[ + resources.DvrSession(), + resources.DvrSession(), + ], + ), + RuntimeError, ) - response = client.get_asset(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = service.GetAssetRequest() - assert args[0] == request - # Establish that the response is the type that we expect. - assert isinstance(response, resources.Asset) - assert response.name == "name_value" - assert response.crc32c == "crc32c_value" - assert response.state == resources.Asset.State.CREATING + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)), + ) + pager = client.list_dvr_sessions(request={}, retry=retry, timeout=timeout) + assert pager._metadata == expected_metadata + assert pager._retry == retry + assert pager._timeout == timeout -def test_get_asset_non_empty_request_with_auto_populated_field(): + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, resources.DvrSession) for i in results) + + +def test_list_dvr_sessions_pages(transport_name: str = "grpc"): + client = LivestreamServiceClient( + 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_dvr_sessions), "__call__" + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + service.ListDvrSessionsResponse( + dvr_sessions=[ + resources.DvrSession(), + resources.DvrSession(), + resources.DvrSession(), + ], + next_page_token="abc", + ), + service.ListDvrSessionsResponse( + dvr_sessions=[], + next_page_token="def", + ), + service.ListDvrSessionsResponse( + dvr_sessions=[ + resources.DvrSession(), + ], + next_page_token="ghi", + ), + service.ListDvrSessionsResponse( + dvr_sessions=[ + resources.DvrSession(), + resources.DvrSession(), + ], + ), + RuntimeError, + ) + pages = list(client.list_dvr_sessions(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_dvr_sessions_async_pager(): + client = LivestreamServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_dvr_sessions), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + service.ListDvrSessionsResponse( + dvr_sessions=[ + resources.DvrSession(), + resources.DvrSession(), + resources.DvrSession(), + ], + next_page_token="abc", + ), + service.ListDvrSessionsResponse( + dvr_sessions=[], + next_page_token="def", + ), + service.ListDvrSessionsResponse( + dvr_sessions=[ + resources.DvrSession(), + ], + next_page_token="ghi", + ), + service.ListDvrSessionsResponse( + dvr_sessions=[ + resources.DvrSession(), + resources.DvrSession(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_dvr_sessions( + 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, resources.DvrSession) for i in responses) + + +@pytest.mark.asyncio +async def test_list_dvr_sessions_async_pages(): + client = LivestreamServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_dvr_sessions), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + service.ListDvrSessionsResponse( + dvr_sessions=[ + resources.DvrSession(), + resources.DvrSession(), + resources.DvrSession(), + ], + next_page_token="abc", + ), + service.ListDvrSessionsResponse( + dvr_sessions=[], + next_page_token="def", + ), + service.ListDvrSessionsResponse( + dvr_sessions=[ + resources.DvrSession(), + ], + next_page_token="ghi", + ), + service.ListDvrSessionsResponse( + dvr_sessions=[ + resources.DvrSession(), + resources.DvrSession(), + ], + ), + RuntimeError, + ) + pages = [] + # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` + # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 + async for page_ in ( # pragma: no branch + await client.list_dvr_sessions(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", + [ + service.GetDvrSessionRequest, + dict, + ], +) +def test_get_dvr_session(request_type, transport: str = "grpc"): + client = LivestreamServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_dvr_session), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = resources.DvrSession( + name="name_value", + state=resources.DvrSession.State.PENDING, + ) + response = client.get_dvr_session(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = service.GetDvrSessionRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.DvrSession) + assert response.name == "name_value" + assert response.state == resources.DvrSession.State.PENDING + + +def test_get_dvr_session_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. client = LivestreamServiceClient( @@ -9343,24 +9583,24 @@ def test_get_asset_non_empty_request_with_auto_populated_field(): # Populate all string fields in the request which are not UUID4 # since we want to check that UUID4 are populated automatically # if they meet the requirements of AIP 4235. - request = service.GetAssetRequest( + request = service.GetDvrSessionRequest( name="name_value", ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_asset), "__call__") as call: + with mock.patch.object(type(client.transport.get_dvr_session), "__call__") as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.get_asset(request=request) + client.get_dvr_session(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == service.GetAssetRequest( + assert args[0] == service.GetDvrSessionRequest( name="name_value", ) -def test_get_asset_use_cached_wrapped_rpc(): +def test_get_dvr_session_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -9374,21 +9614,21 @@ def test_get_asset_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.get_asset in client._transport._wrapped_methods + assert client._transport.get_dvr_session in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = 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_asset] = mock_rpc + client._transport._wrapped_methods[client._transport.get_dvr_session] = mock_rpc request = {} - client.get_asset(request) + client.get_dvr_session(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.get_asset(request) + client.get_dvr_session(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -9396,7 +9636,9 @@ def test_get_asset_use_cached_wrapped_rpc(): @pytest.mark.asyncio -async def test_get_asset_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): +async def test_get_dvr_session_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: @@ -9411,7 +9653,7 @@ async def test_get_asset_async_use_cached_wrapped_rpc(transport: str = "grpc_asy # Ensure method has been cached assert ( - client._client._transport.get_asset + client._client._transport.get_dvr_session in client._client._transport._wrapped_methods ) @@ -9419,16 +9661,16 @@ async def test_get_asset_async_use_cached_wrapped_rpc(transport: str = "grpc_asy mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() client._client._transport._wrapped_methods[ - client._client._transport.get_asset + client._client._transport.get_dvr_session ] = mock_rpc request = {} - await client.get_asset(request) + await client.get_dvr_session(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - await client.get_asset(request) + await client.get_dvr_session(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -9436,8 +9678,8 @@ async def test_get_asset_async_use_cached_wrapped_rpc(transport: str = "grpc_asy @pytest.mark.asyncio -async def test_get_asset_async( - transport: str = "grpc_asyncio", request_type=service.GetAssetRequest +async def test_get_dvr_session_async( + transport: str = "grpc_asyncio", request_type=service.GetDvrSessionRequest ): client = LivestreamServiceAsyncClient( credentials=async_anonymous_credentials(), @@ -9449,50 +9691,48 @@ async def test_get_asset_async( request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_asset), "__call__") as call: + with mock.patch.object(type(client.transport.get_dvr_session), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - resources.Asset( + resources.DvrSession( name="name_value", - crc32c="crc32c_value", - state=resources.Asset.State.CREATING, + state=resources.DvrSession.State.PENDING, ) ) - response = await client.get_asset(request) + response = await client.get_dvr_session(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request = service.GetAssetRequest() + request = service.GetDvrSessionRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, resources.Asset) + assert isinstance(response, resources.DvrSession) assert response.name == "name_value" - assert response.crc32c == "crc32c_value" - assert response.state == resources.Asset.State.CREATING + assert response.state == resources.DvrSession.State.PENDING @pytest.mark.asyncio -async def test_get_asset_async_from_dict(): - await test_get_asset_async(request_type=dict) +async def test_get_dvr_session_async_from_dict(): + await test_get_dvr_session_async(request_type=dict) -def test_get_asset_field_headers(): +def test_get_dvr_session_field_headers(): client = LivestreamServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = service.GetAssetRequest() + request = service.GetDvrSessionRequest() request.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_asset), "__call__") as call: - call.return_value = resources.Asset() - client.get_asset(request) + with mock.patch.object(type(client.transport.get_dvr_session), "__call__") as call: + call.return_value = resources.DvrSession() + client.get_dvr_session(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 @@ -9508,21 +9748,23 @@ def test_get_asset_field_headers(): @pytest.mark.asyncio -async def test_get_asset_field_headers_async(): +async def test_get_dvr_session_field_headers_async(): client = LivestreamServiceAsyncClient( credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = service.GetAssetRequest() + request = service.GetDvrSessionRequest() request.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_asset), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.Asset()) - await client.get_asset(request) + with mock.patch.object(type(client.transport.get_dvr_session), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + resources.DvrSession() + ) + await client.get_dvr_session(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) @@ -9537,18 +9779,18 @@ async def test_get_asset_field_headers_async(): ) in kw["metadata"] -def test_get_asset_flattened(): +def test_get_dvr_session_flattened(): client = LivestreamServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_asset), "__call__") as call: + with mock.patch.object(type(client.transport.get_dvr_session), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = resources.Asset() + call.return_value = resources.DvrSession() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - client.get_asset( + client.get_dvr_session( name="name_value", ) @@ -9561,7 +9803,7 @@ def test_get_asset_flattened(): assert arg == mock_val -def test_get_asset_flattened_error(): +def test_get_dvr_session_flattened_error(): client = LivestreamServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -9569,27 +9811,29 @@ def test_get_asset_flattened_error(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.get_asset( - service.GetAssetRequest(), + client.get_dvr_session( + service.GetDvrSessionRequest(), name="name_value", ) @pytest.mark.asyncio -async def test_get_asset_flattened_async(): +async def test_get_dvr_session_flattened_async(): client = LivestreamServiceAsyncClient( credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_asset), "__call__") as call: + with mock.patch.object(type(client.transport.get_dvr_session), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = resources.Asset() + call.return_value = resources.DvrSession() - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.Asset()) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + resources.DvrSession() + ) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - response = await client.get_asset( + response = await client.get_dvr_session( name="name_value", ) @@ -9603,7 +9847,7 @@ async def test_get_asset_flattened_async(): @pytest.mark.asyncio -async def test_get_asset_flattened_error_async(): +async def test_get_dvr_session_flattened_error_async(): client = LivestreamServiceAsyncClient( credentials=async_anonymous_credentials(), ) @@ -9611,8 +9855,8 @@ async def test_get_asset_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_asset( - service.GetAssetRequest(), + await client.get_dvr_session( + service.GetDvrSessionRequest(), name="name_value", ) @@ -9620,11 +9864,11 @@ async def test_get_asset_flattened_error_async(): @pytest.mark.parametrize( "request_type", [ - service.ListAssetsRequest, + service.DeleteDvrSessionRequest, dict, ], ) -def test_list_assets(request_type, transport: str = "grpc"): +def test_delete_dvr_session(request_type, transport: str = "grpc"): client = LivestreamServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -9635,27 +9879,24 @@ def test_list_assets(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_assets), "__call__") as call: + with mock.patch.object( + type(client.transport.delete_dvr_session), "__call__" + ) as call: # Designate an appropriate return value for the call. - call.return_value = service.ListAssetsResponse( - next_page_token="next_page_token_value", - unreachable=["unreachable_value"], - ) - response = client.list_assets(request) + call.return_value = operations_pb2.Operation(name="operations/spam") + response = client.delete_dvr_session(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - request = service.ListAssetsRequest() + request = service.DeleteDvrSessionRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListAssetsPager) - assert response.next_page_token == "next_page_token_value" - assert response.unreachable == ["unreachable_value"] + assert isinstance(response, future.Future) -def test_list_assets_non_empty_request_with_auto_populated_field(): +def test_delete_dvr_session_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. client = LivestreamServiceClient( @@ -9666,30 +9907,26 @@ def test_list_assets_non_empty_request_with_auto_populated_field(): # Populate all string fields in the request which are not UUID4 # since we want to check that UUID4 are populated automatically # if they meet the requirements of AIP 4235. - request = service.ListAssetsRequest( - parent="parent_value", - page_token="page_token_value", - filter="filter_value", - order_by="order_by_value", + request = service.DeleteDvrSessionRequest( + name="name_value", ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_assets), "__call__") as call: + with mock.patch.object( + type(client.transport.delete_dvr_session), "__call__" + ) as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.list_assets(request=request) + client.delete_dvr_session(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == service.ListAssetsRequest( - parent="parent_value", - page_token="page_token_value", - filter="filter_value", - order_by="order_by_value", + assert args[0] == service.DeleteDvrSessionRequest( + name="name_value", ) -def test_list_assets_use_cached_wrapped_rpc(): +def test_delete_dvr_session_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -9703,21 +9940,30 @@ def test_list_assets_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.list_assets in client._transport._wrapped_methods + assert ( + client._transport.delete_dvr_session in client._transport._wrapped_methods + ) # Replace cached wrapped function with mock mock_rpc = 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_assets] = mock_rpc + client._transport._wrapped_methods[ + client._transport.delete_dvr_session + ] = mock_rpc request = {} - client.list_assets(request) + client.delete_dvr_session(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.list_assets(request) + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.delete_dvr_session(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -9725,7 +9971,7 @@ def test_list_assets_use_cached_wrapped_rpc(): @pytest.mark.asyncio -async def test_list_assets_async_use_cached_wrapped_rpc( +async def test_delete_dvr_session_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", ): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, @@ -9742,7 +9988,7 @@ async def test_list_assets_async_use_cached_wrapped_rpc( # Ensure method has been cached assert ( - client._client._transport.list_assets + client._client._transport.delete_dvr_session in client._client._transport._wrapped_methods ) @@ -9750,16 +9996,21 @@ async def test_list_assets_async_use_cached_wrapped_rpc( mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() client._client._transport._wrapped_methods[ - client._client._transport.list_assets + client._client._transport.delete_dvr_session ] = mock_rpc request = {} - await client.list_assets(request) + await client.delete_dvr_session(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - await client.list_assets(request) + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.delete_dvr_session(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -9767,8 +10018,8 @@ async def test_list_assets_async_use_cached_wrapped_rpc( @pytest.mark.asyncio -async def test_list_assets_async( - transport: str = "grpc_asyncio", request_type=service.ListAssetsRequest +async def test_delete_dvr_session_async( + transport: str = "grpc_asyncio", request_type=service.DeleteDvrSessionRequest ): client = LivestreamServiceAsyncClient( credentials=async_anonymous_credentials(), @@ -9780,48 +10031,47 @@ async def test_list_assets_async( request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_assets), "__call__") as call: + with mock.patch.object( + type(client.transport.delete_dvr_session), "__call__" + ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - service.ListAssetsResponse( - next_page_token="next_page_token_value", - unreachable=["unreachable_value"], - ) + operations_pb2.Operation(name="operations/spam") ) - response = await client.list_assets(request) + response = await client.delete_dvr_session(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request = service.ListAssetsRequest() + request = service.DeleteDvrSessionRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListAssetsAsyncPager) - assert response.next_page_token == "next_page_token_value" - assert response.unreachable == ["unreachable_value"] + assert isinstance(response, future.Future) @pytest.mark.asyncio -async def test_list_assets_async_from_dict(): - await test_list_assets_async(request_type=dict) +async def test_delete_dvr_session_async_from_dict(): + await test_delete_dvr_session_async(request_type=dict) -def test_list_assets_field_headers(): +def test_delete_dvr_session_field_headers(): client = LivestreamServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = service.ListAssetsRequest() + request = service.DeleteDvrSessionRequest() - 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_assets), "__call__") as call: - call.return_value = service.ListAssetsResponse() - client.list_assets(request) + with mock.patch.object( + type(client.transport.delete_dvr_session), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.delete_dvr_session(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 @@ -9832,28 +10082,30 @@ def test_list_assets_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_assets_field_headers_async(): +async def test_delete_dvr_session_field_headers_async(): client = LivestreamServiceAsyncClient( credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = service.ListAssetsRequest() + request = service.DeleteDvrSessionRequest() - 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_assets), "__call__") as call: + with mock.patch.object( + type(client.transport.delete_dvr_session), "__call__" + ) as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - service.ListAssetsResponse() + operations_pb2.Operation(name="operations/op") ) - await client.list_assets(request) + await client.delete_dvr_session(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) @@ -9864,35 +10116,37 @@ async def test_list_assets_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_assets_flattened(): +def test_delete_dvr_session_flattened(): client = LivestreamServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_assets), "__call__") as call: + with mock.patch.object( + type(client.transport.delete_dvr_session), "__call__" + ) as call: # Designate an appropriate return value for the call. - call.return_value = service.ListAssetsResponse() + call.return_value = operations_pb2.Operation(name="operations/op") # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - client.list_assets( - parent="parent_value", + client.delete_dvr_session( + 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_assets_flattened_error(): +def test_delete_dvr_session_flattened_error(): client = LivestreamServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -9900,43 +10154,45 @@ def test_list_assets_flattened_error(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.list_assets( - service.ListAssetsRequest(), - parent="parent_value", + client.delete_dvr_session( + service.DeleteDvrSessionRequest(), + name="name_value", ) @pytest.mark.asyncio -async def test_list_assets_flattened_async(): +async def test_delete_dvr_session_flattened_async(): client = LivestreamServiceAsyncClient( credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_assets), "__call__") as call: + with mock.patch.object( + type(client.transport.delete_dvr_session), "__call__" + ) as call: # Designate an appropriate return value for the call. - call.return_value = service.ListAssetsResponse() + call.return_value = operations_pb2.Operation(name="operations/op") call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - service.ListAssetsResponse() + operations_pb2.Operation(name="operations/spam") ) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - response = await client.list_assets( - parent="parent_value", + response = await client.delete_dvr_session( + 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_assets_flattened_error_async(): +async def test_delete_dvr_session_flattened_error_async(): client = LivestreamServiceAsyncClient( credentials=async_anonymous_credentials(), ) @@ -9944,299 +10200,111 @@ async def test_list_assets_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_assets( - service.ListAssetsRequest(), - parent="parent_value", + await client.delete_dvr_session( + service.DeleteDvrSessionRequest(), + name="name_value", ) -def test_list_assets_pager(transport_name: str = "grpc"): +@pytest.mark.parametrize( + "request_type", + [ + service.UpdateDvrSessionRequest, + dict, + ], +) +def test_update_dvr_session(request_type, transport: str = "grpc"): client = LivestreamServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport=transport_name, + transport=transport, ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_assets), "__call__") as call: - # Set the response to a series of pages. - call.side_effect = ( - service.ListAssetsResponse( - assets=[ - resources.Asset(), - resources.Asset(), - resources.Asset(), - ], - next_page_token="abc", - ), - service.ListAssetsResponse( - assets=[], - next_page_token="def", - ), - service.ListAssetsResponse( - assets=[ - resources.Asset(), - ], - next_page_token="ghi", - ), - service.ListAssetsResponse( - assets=[ - resources.Asset(), - resources.Asset(), - ], - ), - RuntimeError, - ) + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() - expected_metadata = () - retry = retries.Retry() - timeout = 5 - expected_metadata = tuple(expected_metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)), - ) - pager = client.list_assets(request={}, retry=retry, timeout=timeout) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_dvr_session), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/spam") + response = client.update_dvr_session(request) - assert pager._metadata == expected_metadata - assert pager._retry == retry - assert pager._timeout == timeout + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = service.UpdateDvrSessionRequest() + assert args[0] == request - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, resources.Asset) for i in results) + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) -def test_list_assets_pages(transport_name: str = "grpc"): +def test_update_dvr_session_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. client = LivestreamServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport=transport_name, + transport="grpc", ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_assets), "__call__") as call: - # Set the response to a series of pages. - call.side_effect = ( - service.ListAssetsResponse( - assets=[ - resources.Asset(), - resources.Asset(), - resources.Asset(), - ], - next_page_token="abc", - ), - service.ListAssetsResponse( - assets=[], - next_page_token="def", - ), - service.ListAssetsResponse( - assets=[ - resources.Asset(), - ], - next_page_token="ghi", - ), - service.ListAssetsResponse( - assets=[ - resources.Asset(), - resources.Asset(), - ], - ), - RuntimeError, - ) - pages = list(client.list_assets(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_assets_async_pager(): - client = LivestreamServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = service.UpdateDvrSessionRequest() # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_assets), "__call__", new_callable=mock.AsyncMock + type(client.transport.update_dvr_session), "__call__" ) as call: - # Set the response to a series of pages. - call.side_effect = ( - service.ListAssetsResponse( - assets=[ - resources.Asset(), - resources.Asset(), - resources.Asset(), - ], - next_page_token="abc", - ), - service.ListAssetsResponse( - assets=[], - next_page_token="def", - ), - service.ListAssetsResponse( - assets=[ - resources.Asset(), - ], - next_page_token="ghi", - ), - service.ListAssetsResponse( - assets=[ - resources.Asset(), - resources.Asset(), - ], - ), - RuntimeError, + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. ) - async_pager = await client.list_assets( - request={}, + client.update_dvr_session(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == service.UpdateDvrSessionRequest() + + +def test_update_dvr_session_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = LivestreamServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", ) - 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, resources.Asset) for i in responses) + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + # Ensure method has been cached + assert ( + client._transport.update_dvr_session in client._transport._wrapped_methods + ) -@pytest.mark.asyncio -async def test_list_assets_async_pages(): - client = LivestreamServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_assets), "__call__", new_callable=mock.AsyncMock - ) as call: - # Set the response to a series of pages. - call.side_effect = ( - service.ListAssetsResponse( - assets=[ - resources.Asset(), - resources.Asset(), - resources.Asset(), - ], - next_page_token="abc", - ), - service.ListAssetsResponse( - assets=[], - next_page_token="def", - ), - service.ListAssetsResponse( - assets=[ - resources.Asset(), - ], - next_page_token="ghi", - ), - service.ListAssetsResponse( - assets=[ - resources.Asset(), - resources.Asset(), - ], - ), - RuntimeError, - ) - pages = [] - # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` - # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 - async for page_ in ( # pragma: no branch - await client.list_assets(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", - [ - service.GetPoolRequest, - dict, - ], -) -def test_get_pool(request_type, transport: str = "grpc"): - client = LivestreamServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_pool), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = resources.Pool( - name="name_value", - ) - response = client.get_pool(request) + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.update_dvr_session + ] = mock_rpc + request = {} + client.update_dvr_session(request) # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = service.GetPoolRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, resources.Pool) - assert response.name == "name_value" - - -def test_get_pool_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = LivestreamServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = service.GetPoolRequest( - name="name_value", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_pool), "__call__") as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.get_pool(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == service.GetPoolRequest( - name="name_value", - ) - - -def test_get_pool_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = LivestreamServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) + assert mock_rpc.call_count == 1 - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper wrapper_fn.reset_mock() - # Ensure method has been cached - assert client._transport.get_pool in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_pool] = mock_rpc - request = {} - client.get_pool(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_pool(request) + client.update_dvr_session(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -10244,7 +10312,9 @@ def test_get_pool_use_cached_wrapped_rpc(): @pytest.mark.asyncio -async def test_get_pool_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): +async def test_update_dvr_session_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: @@ -10259,7 +10329,7 @@ async def test_get_pool_async_use_cached_wrapped_rpc(transport: str = "grpc_asyn # Ensure method has been cached assert ( - client._client._transport.get_pool + client._client._transport.update_dvr_session in client._client._transport._wrapped_methods ) @@ -10267,16 +10337,21 @@ async def test_get_pool_async_use_cached_wrapped_rpc(transport: str = "grpc_asyn mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() client._client._transport._wrapped_methods[ - client._client._transport.get_pool + client._client._transport.update_dvr_session ] = mock_rpc request = {} - await client.get_pool(request) + await client.update_dvr_session(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - await client.get_pool(request) + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.update_dvr_session(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -10284,8 +10359,8 @@ async def test_get_pool_async_use_cached_wrapped_rpc(transport: str = "grpc_asyn @pytest.mark.asyncio -async def test_get_pool_async( - transport: str = "grpc_asyncio", request_type=service.GetPoolRequest +async def test_update_dvr_session_async( + transport: str = "grpc_asyncio", request_type=service.UpdateDvrSessionRequest ): client = LivestreamServiceAsyncClient( credentials=async_anonymous_credentials(), @@ -10297,46 +10372,47 @@ async def test_get_pool_async( request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_pool), "__call__") as call: + with mock.patch.object( + type(client.transport.update_dvr_session), "__call__" + ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - resources.Pool( - name="name_value", - ) + operations_pb2.Operation(name="operations/spam") ) - response = await client.get_pool(request) + response = await client.update_dvr_session(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request = service.GetPoolRequest() + request = service.UpdateDvrSessionRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, resources.Pool) - assert response.name == "name_value" + assert isinstance(response, future.Future) @pytest.mark.asyncio -async def test_get_pool_async_from_dict(): - await test_get_pool_async(request_type=dict) +async def test_update_dvr_session_async_from_dict(): + await test_update_dvr_session_async(request_type=dict) -def test_get_pool_field_headers(): +def test_update_dvr_session_field_headers(): client = LivestreamServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = service.GetPoolRequest() + request = service.UpdateDvrSessionRequest() - request.name = "name_value" + request.dvr_session.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_pool), "__call__") as call: - call.return_value = resources.Pool() - client.get_pool(request) + with mock.patch.object( + type(client.transport.update_dvr_session), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.update_dvr_session(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 @@ -10347,26 +10423,30 @@ def test_get_pool_field_headers(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "name=name_value", + "dvr_session.name=name_value", ) in kw["metadata"] @pytest.mark.asyncio -async def test_get_pool_field_headers_async(): +async def test_update_dvr_session_field_headers_async(): client = LivestreamServiceAsyncClient( credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = service.GetPoolRequest() + request = service.UpdateDvrSessionRequest() - request.name = "name_value" + request.dvr_session.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_pool), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.Pool()) - await client.get_pool(request) + with mock.patch.object( + type(client.transport.update_dvr_session), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/op") + ) + await client.update_dvr_session(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) @@ -10377,35 +10457,41 @@ async def test_get_pool_field_headers_async(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "name=name_value", + "dvr_session.name=name_value", ) in kw["metadata"] -def test_get_pool_flattened(): +def test_update_dvr_session_flattened(): client = LivestreamServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_pool), "__call__") as call: + with mock.patch.object( + type(client.transport.update_dvr_session), "__call__" + ) as call: # Designate an appropriate return value for the call. - call.return_value = resources.Pool() + call.return_value = operations_pb2.Operation(name="operations/op") # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - client.get_pool( - name="name_value", + client.update_dvr_session( + dvr_session=resources.DvrSession(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) # Establish that the underlying call was made with the expected # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = "name_value" + arg = args[0].dvr_session + mock_val = resources.DvrSession(name="name_value") + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=["paths_value"]) assert arg == mock_val -def test_get_pool_flattened_error(): +def test_update_dvr_session_flattened_error(): client = LivestreamServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -10413,41 +10499,50 @@ def test_get_pool_flattened_error(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.get_pool( - service.GetPoolRequest(), - name="name_value", + client.update_dvr_session( + service.UpdateDvrSessionRequest(), + dvr_session=resources.DvrSession(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) @pytest.mark.asyncio -async def test_get_pool_flattened_async(): +async def test_update_dvr_session_flattened_async(): client = LivestreamServiceAsyncClient( credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_pool), "__call__") as call: + with mock.patch.object( + type(client.transport.update_dvr_session), "__call__" + ) as call: # Designate an appropriate return value for the call. - call.return_value = resources.Pool() + call.return_value = operations_pb2.Operation(name="operations/op") - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.Pool()) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - response = await client.get_pool( - name="name_value", + response = await client.update_dvr_session( + dvr_session=resources.DvrSession(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) # Establish that the underlying call was made with the expected # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = "name_value" + arg = args[0].dvr_session + mock_val = resources.DvrSession(name="name_value") + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=["paths_value"]) assert arg == mock_val @pytest.mark.asyncio -async def test_get_pool_flattened_error_async(): +async def test_update_dvr_session_flattened_error_async(): client = LivestreamServiceAsyncClient( credentials=async_anonymous_credentials(), ) @@ -10455,20 +10550,21 @@ async def test_get_pool_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_pool( - service.GetPoolRequest(), - name="name_value", + await client.update_dvr_session( + service.UpdateDvrSessionRequest(), + dvr_session=resources.DvrSession(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) @pytest.mark.parametrize( "request_type", [ - service.UpdatePoolRequest, + service.CreateAssetRequest, dict, ], ) -def test_update_pool(request_type, transport: str = "grpc"): +def test_create_asset(request_type, transport: str = "grpc"): client = LivestreamServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -10479,22 +10575,22 @@ def test_update_pool(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_pool), "__call__") as call: + with mock.patch.object(type(client.transport.create_asset), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = operations_pb2.Operation(name="operations/spam") - response = client.update_pool(request) + response = client.create_asset(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - request = service.UpdatePoolRequest() + request = service.CreateAssetRequest() assert args[0] == request # Establish that the response is the type that we expect. assert isinstance(response, future.Future) -def test_update_pool_non_empty_request_with_auto_populated_field(): +def test_create_asset_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. client = LivestreamServiceClient( @@ -10505,24 +10601,28 @@ def test_update_pool_non_empty_request_with_auto_populated_field(): # Populate all string fields in the request which are not UUID4 # since we want to check that UUID4 are populated automatically # if they meet the requirements of AIP 4235. - request = service.UpdatePoolRequest( + request = service.CreateAssetRequest( + parent="parent_value", + asset_id="asset_id_value", request_id="request_id_value", ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.update_pool), "__call__") as call: + with mock.patch.object(type(client.transport.create_asset), "__call__") as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.update_pool(request=request) + client.create_asset(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == service.UpdatePoolRequest( + assert args[0] == service.CreateAssetRequest( + parent="parent_value", + asset_id="asset_id_value", request_id="request_id_value", ) -def test_update_pool_use_cached_wrapped_rpc(): +def test_create_asset_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -10536,16 +10636,16 @@ def test_update_pool_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.update_pool in client._transport._wrapped_methods + assert client._transport.create_asset in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = 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_pool] = mock_rpc + client._transport._wrapped_methods[client._transport.create_asset] = mock_rpc request = {} - client.update_pool(request) + client.create_asset(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 @@ -10555,7 +10655,7 @@ def test_update_pool_use_cached_wrapped_rpc(): # Subsequent calls should use the cached wrapper wrapper_fn.reset_mock() - client.update_pool(request) + client.create_asset(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -10563,7 +10663,7 @@ def test_update_pool_use_cached_wrapped_rpc(): @pytest.mark.asyncio -async def test_update_pool_async_use_cached_wrapped_rpc( +async def test_create_asset_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", ): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, @@ -10580,7 +10680,7 @@ async def test_update_pool_async_use_cached_wrapped_rpc( # Ensure method has been cached assert ( - client._client._transport.update_pool + client._client._transport.create_asset in client._client._transport._wrapped_methods ) @@ -10588,11 +10688,11 @@ async def test_update_pool_async_use_cached_wrapped_rpc( mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() client._client._transport._wrapped_methods[ - client._client._transport.update_pool + client._client._transport.create_asset ] = mock_rpc request = {} - await client.update_pool(request) + await client.create_asset(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 @@ -10602,7 +10702,7 @@ async def test_update_pool_async_use_cached_wrapped_rpc( # Subsequent calls should use the cached wrapper wrapper_fn.reset_mock() - await client.update_pool(request) + await client.create_asset(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -10610,8 +10710,8 @@ async def test_update_pool_async_use_cached_wrapped_rpc( @pytest.mark.asyncio -async def test_update_pool_async( - transport: str = "grpc_asyncio", request_type=service.UpdatePoolRequest +async def test_create_asset_async( + transport: str = "grpc_asyncio", request_type=service.CreateAssetRequest ): client = LivestreamServiceAsyncClient( credentials=async_anonymous_credentials(), @@ -10623,17 +10723,17 @@ async def test_update_pool_async( request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.update_pool), "__call__") as call: + with mock.patch.object(type(client.transport.create_asset), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( operations_pb2.Operation(name="operations/spam") ) - response = await client.update_pool(request) + response = await client.create_asset(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request = service.UpdatePoolRequest() + request = service.CreateAssetRequest() assert args[0] == request # Establish that the response is the type that we expect. @@ -10641,25 +10741,25 @@ async def test_update_pool_async( @pytest.mark.asyncio -async def test_update_pool_async_from_dict(): - await test_update_pool_async(request_type=dict) +async def test_create_asset_async_from_dict(): + await test_create_asset_async(request_type=dict) -def test_update_pool_field_headers(): +def test_create_asset_field_headers(): client = LivestreamServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = service.UpdatePoolRequest() + request = service.CreateAssetRequest() - request.pool.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_pool), "__call__") as call: + with mock.patch.object(type(client.transport.create_asset), "__call__") as call: call.return_value = operations_pb2.Operation(name="operations/op") - client.update_pool(request) + client.create_asset(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 @@ -10670,28 +10770,28 @@ def test_update_pool_field_headers(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "pool.name=name_value", + "parent=parent_value", ) in kw["metadata"] @pytest.mark.asyncio -async def test_update_pool_field_headers_async(): +async def test_create_asset_field_headers_async(): client = LivestreamServiceAsyncClient( credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = service.UpdatePoolRequest() + request = service.CreateAssetRequest() - request.pool.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_pool), "__call__") as call: + with mock.patch.object(type(client.transport.create_asset), "__call__") as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( operations_pb2.Operation(name="operations/op") ) - await client.update_pool(request) + await client.create_asset(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) @@ -10702,39 +10802,43 @@ async def test_update_pool_field_headers_async(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "pool.name=name_value", + "parent=parent_value", ) in kw["metadata"] -def test_update_pool_flattened(): +def test_create_asset_flattened(): client = LivestreamServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.update_pool), "__call__") as call: + with mock.patch.object(type(client.transport.create_asset), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = operations_pb2.Operation(name="operations/op") # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - client.update_pool( - pool=resources.Pool(name="name_value"), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + client.create_asset( + parent="parent_value", + asset=resources.Asset(name="name_value"), + asset_id="asset_id_value", ) # Establish that the underlying call was made with the expected # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - arg = args[0].pool - mock_val = resources.Pool(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].asset + mock_val = resources.Asset(name="name_value") + assert arg == mock_val + arg = args[0].asset_id + mock_val = "asset_id_value" assert arg == mock_val -def test_update_pool_flattened_error(): +def test_create_asset_flattened_error(): client = LivestreamServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -10742,21 +10846,22 @@ def test_update_pool_flattened_error(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.update_pool( - service.UpdatePoolRequest(), - pool=resources.Pool(name="name_value"), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + client.create_asset( + service.CreateAssetRequest(), + parent="parent_value", + asset=resources.Asset(name="name_value"), + asset_id="asset_id_value", ) @pytest.mark.asyncio -async def test_update_pool_flattened_async(): +async def test_create_asset_flattened_async(): client = LivestreamServiceAsyncClient( credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.update_pool), "__call__") as call: + with mock.patch.object(type(client.transport.create_asset), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = operations_pb2.Operation(name="operations/op") @@ -10765,25 +10870,29 @@ async def test_update_pool_flattened_async(): ) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - response = await client.update_pool( - pool=resources.Pool(name="name_value"), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + response = await client.create_asset( + parent="parent_value", + asset=resources.Asset(name="name_value"), + asset_id="asset_id_value", ) # Establish that the underlying call was made with the expected # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - arg = args[0].pool - mock_val = resources.Pool(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].asset + mock_val = resources.Asset(name="name_value") + assert arg == mock_val + arg = args[0].asset_id + mock_val = "asset_id_value" assert arg == mock_val @pytest.mark.asyncio -async def test_update_pool_flattened_error_async(): +async def test_create_asset_flattened_error_async(): client = LivestreamServiceAsyncClient( credentials=async_anonymous_credentials(), ) @@ -10791,20 +10900,84 @@ async def test_update_pool_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_pool( - service.UpdatePoolRequest(), - pool=resources.Pool(name="name_value"), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + await client.create_asset( + service.CreateAssetRequest(), + parent="parent_value", + asset=resources.Asset(name="name_value"), + asset_id="asset_id_value", ) -def test_create_channel_rest_use_cached_wrapped_rpc(): +@pytest.mark.parametrize( + "request_type", + [ + service.DeleteAssetRequest, + dict, + ], +) +def test_delete_asset(request_type, transport: str = "grpc"): + client = LivestreamServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_asset), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/spam") + response = client.delete_asset(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = service.DeleteAssetRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_delete_asset_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = LivestreamServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = service.DeleteAssetRequest( + name="name_value", + request_id="request_id_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_asset), "__call__") as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.delete_asset(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == service.DeleteAssetRequest( + name="name_value", + request_id="request_id_value", + ) + + +def test_delete_asset_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: client = LivestreamServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport="grpc", ) # Should wrap all calls on client creation @@ -10812,642 +10985,662 @@ def test_create_channel_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.create_channel_ in client._transport._wrapped_methods + assert client._transport.delete_asset in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = 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_channel_] = mock_rpc - + client._transport._wrapped_methods[client._transport.delete_asset] = mock_rpc request = {} - client.create_channel(request) + client.delete_asset(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - # Operation methods build a cached wrapper on first rpc call - # subsequent calls should use the cached wrapper + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper wrapper_fn.reset_mock() - client.create_channel(request) + client.delete_asset(request) # Establish 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_channel_rest_required_fields(request_type=service.CreateChannelRequest): - transport_class = transports.LivestreamServiceRestTransport +@pytest.mark.asyncio +async def test_delete_asset_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 = LivestreamServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) - request_init = {} - request_init["parent"] = "" - request_init["channel_id"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads( - json_format.MessageToJson(pb_request, use_integers_for_enums=False) - ) + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() - # verify fields with default values are dropped - assert "channelId" not in jsonified_request + # Ensure method has been cached + assert ( + client._client._transport.delete_asset + in client._client._transport._wrapped_methods + ) - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).create_channel_._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.delete_asset + ] = mock_rpc - # verify required fields with default values are now present - assert "channelId" in jsonified_request - assert jsonified_request["channelId"] == request_init["channel_id"] + request = {} + await client.delete_asset(request) - jsonified_request["parent"] = "parent_value" - jsonified_request["channelId"] = "channel_id_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_channel_._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set( - ( - "channel_id", - "request_id", - ) + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.delete_asset(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_delete_asset_async( + transport: str = "grpc_asyncio", request_type=service.DeleteAssetRequest +): + client = LivestreamServiceAsyncClient( + 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" - assert "channelId" in jsonified_request - assert jsonified_request["channelId"] == "channel_id_value" + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_asset), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + response = await client.delete_asset(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = service.DeleteAssetRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_delete_asset_async_from_dict(): + await test_delete_asset_async(request_type=dict) + +def test_delete_asset_field_headers(): client = LivestreamServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", ) - request = request_type(**request_init) - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name="operations/spam") - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, "request") as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, "transcode") as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - "uri": "v1/sample_method", - "method": "post", - "query_params": pb_request, - } - transcode_result["body"] = pb_request - transcode.return_value = transcode_result + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.DeleteAssetRequest() - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) + request.name = "name_value" - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_asset), "__call__") as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.delete_asset(request) - response = client.create_channel(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 = [ - ( - "channelId", - "", - ), - ("$alt", "json;enum-encoding=int"), - ] - actual_params = req.call_args.kwargs["params"] - assert expected_params == actual_params + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] -def test_create_channel_rest_unset_required_fields(): - transport = transports.LivestreamServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials +@pytest.mark.asyncio +async def test_delete_asset_field_headers_async(): + client = LivestreamServiceAsyncClient( + credentials=async_anonymous_credentials(), ) - unset_fields = transport.create_channel_._get_unset_required_fields({}) - assert set(unset_fields) == ( - set( - ( - "channelId", - "requestId", - ) - ) - & set( - ( - "parent", - "channel", - "channelId", - ) + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.DeleteAssetRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_asset), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/op") ) - ) + await client.delete_asset(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_create_channel_rest_flattened(): + +def test_delete_asset_flattened(): client = LivestreamServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", ) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), "request") as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name="operations/spam") - - # get arguments that satisfy an http rule for this method - sample_request = {"parent": "projects/sample1/locations/sample2"} - - # get truthy value for each flattened field - mock_args = dict( - parent="parent_value", - channel=resources.Channel(name="name_value"), - channel_id="channel_id_value", + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_asset), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/op") + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.delete_asset( + name="name_value", ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - client.create_channel(**mock_args) # Establish that the underlying call was 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/*}/channels" % client.transport._host, - args[1], - ) + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val -def test_create_channel_rest_flattened_error(transport: str = "rest"): +def test_delete_asset_flattened_error(): client = LivestreamServiceClient( credentials=ga_credentials.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_channel( - service.CreateChannelRequest(), - parent="parent_value", - channel=resources.Channel(name="name_value"), - channel_id="channel_id_value", + client.delete_asset( + service.DeleteAssetRequest(), + name="name_value", ) -def test_list_channels_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = LivestreamServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() +@pytest.mark.asyncio +async def test_delete_asset_flattened_async(): + client = LivestreamServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) - # Ensure method has been cached - assert client._transport.list_channels in client._transport._wrapped_methods + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_asset), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/op") - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.delete_asset( + name="name_value", ) - client._transport._wrapped_methods[client._transport.list_channels] = mock_rpc - request = {} - client.list_channels(request) + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - client.list_channels(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 +@pytest.mark.asyncio +async def test_delete_asset_flattened_error_async(): + client = LivestreamServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.delete_asset( + service.DeleteAssetRequest(), + name="name_value", + ) -def test_list_channels_rest_required_fields(request_type=service.ListChannelsRequest): - transport_class = transports.LivestreamServiceRestTransport - 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", + [ + service.GetAssetRequest, + dict, + ], +) +def test_get_asset(request_type, transport: str = "grpc"): + client = LivestreamServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, ) - # verify fields with default values are dropped - - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).list_channels._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.get_asset), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = resources.Asset( + name="name_value", + crc32c="crc32c_value", + state=resources.Asset.State.CREATING, + ) + response = client.get_asset(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 = service.GetAssetRequest() + assert args[0] == request - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).list_channels._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) + # Establish that the response is the type that we expect. + assert isinstance(response, resources.Asset) + assert response.name == "name_value" + assert response.crc32c == "crc32c_value" + assert response.state == resources.Asset.State.CREATING - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == "parent_value" +def test_get_asset_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. client = LivestreamServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport="grpc", ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = service.ListChannelsResponse() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, "request") as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, "transcode") as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - "uri": "v1/sample_method", - "method": "get", - "query_params": pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = service.ListChannelsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = service.GetAssetRequest( + name="name_value", + ) - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_asset), "__call__") as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.get_asset(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == service.GetAssetRequest( + name="name_value", + ) - response = client.list_channels(request) - expected_params = [("$alt", "json;enum-encoding=int")] - actual_params = req.call_args.kwargs["params"] - assert expected_params == actual_params +def test_get_asset_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = LivestreamServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() -def test_list_channels_rest_unset_required_fields(): - transport = transports.LivestreamServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials - ) + # Ensure method has been cached + assert client._transport.get_asset in client._transport._wrapped_methods - unset_fields = transport.list_channels._get_unset_required_fields({}) - assert set(unset_fields) == ( - set( - ( - "filter", - "orderBy", - "pageSize", - "pageToken", - ) + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. ) - & set(("parent",)) - ) + client._transport._wrapped_methods[client._transport.get_asset] = mock_rpc + request = {} + client.get_asset(request) + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 -def test_list_channels_rest_flattened(): - client = LivestreamServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) + client.get_asset(request) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), "request") as req: - # Designate an appropriate value for the returned response. - return_value = service.ListChannelsResponse() + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 - # 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", +@pytest.mark.asyncio +async def test_get_asset_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 = LivestreamServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = service.ListChannelsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = 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_channels(**mock_args) + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() - # Establish that the underlying call was 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/*}/channels" % client.transport._host, - args[1], + # Ensure method has been cached + assert ( + client._client._transport.get_asset + in client._client._transport._wrapped_methods ) + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.get_asset + ] = mock_rpc -def test_list_channels_rest_flattened_error(transport: str = "rest"): - client = LivestreamServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) + request = {} + await client.get_asset(request) - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.list_channels( - service.ListChannelsRequest(), - parent="parent_value", - ) + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + await client.get_asset(request) -def test_list_channels_rest_pager(transport: str = "rest"): - client = LivestreamServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, "request") as req: - # TODO(kbandes): remove this mock unless there's a good reason for it. - # with mock.patch.object(path_template, 'transcode') as transcode: - # Set the response as a series of pages - response = ( - service.ListChannelsResponse( - channels=[ - resources.Channel(), - resources.Channel(), - resources.Channel(), - ], - next_page_token="abc", - ), - service.ListChannelsResponse( - channels=[], - next_page_token="def", - ), - service.ListChannelsResponse( - channels=[ - resources.Channel(), - ], - next_page_token="ghi", - ), - service.ListChannelsResponse( - channels=[ - resources.Channel(), - resources.Channel(), - ], - ), - ) - # Two responses for two calls - response = response + response - # Wrap the values into proper Response objs - response = tuple(service.ListChannelsResponse.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_channels(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, resources.Channel) for i in results) - - pages = list(client.list_channels(request=sample_request).pages) - for page_, token in zip(pages, ["abc", "def", "ghi", ""]): - assert page_.raw_page.next_page_token == token - - -def test_get_channel_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = LivestreamServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() +@pytest.mark.asyncio +async def test_get_asset_async( + transport: str = "grpc_asyncio", request_type=service.GetAssetRequest +): + client = LivestreamServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) - # Ensure method has been cached - assert client._transport.get_channel in client._transport._wrapped_methods + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() - # Replace cached 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.get_asset), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + resources.Asset( + name="name_value", + crc32c="crc32c_value", + state=resources.Asset.State.CREATING, + ) ) - client._transport._wrapped_methods[client._transport.get_channel] = mock_rpc - - request = {} - client.get_channel(request) + response = await client.get_asset(request) # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = service.GetAssetRequest() + assert args[0] == request - client.get_channel(request) + # Establish that the response is the type that we expect. + assert isinstance(response, resources.Asset) + assert response.name == "name_value" + assert response.crc32c == "crc32c_value" + assert response.state == resources.Asset.State.CREATING - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 +@pytest.mark.asyncio +async def test_get_asset_async_from_dict(): + await test_get_asset_async(request_type=dict) -def test_get_channel_rest_required_fields(request_type=service.GetChannelRequest): - transport_class = transports.LivestreamServiceRestTransport - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads( - json_format.MessageToJson(pb_request, use_integers_for_enums=False) +def test_get_asset_field_headers(): + client = LivestreamServiceClient( + credentials=ga_credentials.AnonymousCredentials(), ) - # verify fields with default values are dropped + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.GetAssetRequest() - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).get_channel._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) + request.name = "name_value" - # verify required fields with default values are now present + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_asset), "__call__") as call: + call.return_value = resources.Asset() + client.get_asset(request) - jsonified_request["name"] = "name_value" + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).get_channel._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", + "name=name_value", + ) in kw["metadata"] - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == "name_value" - client = LivestreamServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", +@pytest.mark.asyncio +async def test_get_asset_field_headers_async(): + client = LivestreamServiceAsyncClient( + credentials=async_anonymous_credentials(), ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = resources.Channel() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, "request") as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, "transcode") as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_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 = service.GetAssetRequest() - # Convert return value to protobuf type - return_value = resources.Channel.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) + request.name = "name_value" - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_asset), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.Asset()) + await client.get_asset(request) - response = client.get_channel(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request - expected_params = [("$alt", "json;enum-encoding=int")] - actual_params = req.call_args.kwargs["params"] - assert expected_params == 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_get_channel_rest_unset_required_fields(): - transport = transports.LivestreamServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials +def test_get_asset_flattened(): + client = LivestreamServiceClient( + credentials=ga_credentials.AnonymousCredentials(), ) - unset_fields = transport.get_channel._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name",))) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_asset), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = resources.Asset() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_asset( + 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_channel_rest_flattened(): +def test_get_asset_flattened_error(): client = LivestreamServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", ) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), "request") as req: - # Designate an appropriate value for the returned response. - return_value = resources.Channel() - - # get arguments that satisfy an http rule for this method - sample_request = {"name": "projects/sample1/locations/sample2/channels/sample3"} - - # get truthy value for each flattened field - mock_args = dict( + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_asset( + service.GetAssetRequest(), name="name_value", ) - mock_args.update(sample_request) - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = resources.Channel.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = 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_channel(**mock_args) +@pytest.mark.asyncio +async def test_get_asset_flattened_async(): + client = LivestreamServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_asset), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = resources.Asset() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.Asset()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_asset( + name="name_value", + ) # Establish that the underlying call was made with the expected # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate( - "%s/v1/{name=projects/*/locations/*/channels/*}" % client.transport._host, - args[1], - ) + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val -def test_get_channel_rest_flattened_error(transport: str = "rest"): - client = LivestreamServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, +@pytest.mark.asyncio +async def test_get_asset_flattened_error_async(): + client = LivestreamServiceAsyncClient( + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.get_channel( - service.GetChannelRequest(), + await client.get_asset( + service.GetAssetRequest(), name="name_value", ) -def test_delete_channel_rest_use_cached_wrapped_rpc(): +@pytest.mark.parametrize( + "request_type", + [ + service.ListAssetsRequest, + dict, + ], +) +def test_list_assets(request_type, transport: str = "grpc"): + client = LivestreamServiceClient( + 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_assets), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = service.ListAssetsResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], + ) + response = client.list_assets(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = service.ListAssetsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListAssetsPager) + assert response.next_page_token == "next_page_token_value" + assert response.unreachable == ["unreachable_value"] + + +def test_list_assets_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = LivestreamServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = service.ListAssetsRequest( + parent="parent_value", + page_token="page_token_value", + filter="filter_value", + order_by="order_by_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_assets), "__call__") as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.list_assets(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == service.ListAssetsRequest( + parent="parent_value", + page_token="page_token_value", + filter="filter_value", + order_by="order_by_value", + ) + + +def test_list_assets_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: client = LivestreamServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport="grpc", ) # Should wrap all calls on client creation @@ -11455,554 +11648,518 @@ def test_delete_channel_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.delete_channel in client._transport._wrapped_methods + assert client._transport.list_assets in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = 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_channel] = mock_rpc - + client._transport._wrapped_methods[client._transport.list_assets] = mock_rpc request = {} - client.delete_channel(request) + client.list_assets(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - # Operation methods build a cached wrapper on first rpc call - # subsequent calls should use the cached wrapper + client.list_assets(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_assets_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 = LivestreamServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 wrapper_fn.reset_mock() - client.delete_channel(request) + # Ensure method has been cached + assert ( + client._client._transport.list_assets + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.list_assets + ] = mock_rpc + + request = {} + await client.list_assets(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.list_assets(request) # Establish 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_channel_rest_required_fields(request_type=service.DeleteChannelRequest): - transport_class = transports.LivestreamServiceRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads( - json_format.MessageToJson(pb_request, use_integers_for_enums=False) +@pytest.mark.asyncio +async def test_list_assets_async( + transport: str = "grpc_asyncio", request_type=service.ListAssetsRequest +): + client = LivestreamServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, ) - # verify fields with default values are dropped + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).delete_channel._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_assets), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + service.ListAssetsResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], + ) + ) + response = await client.list_assets(request) - # verify required fields with default values are now present + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = service.ListAssetsRequest() + assert args[0] == request - jsonified_request["name"] = "name_value" + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListAssetsAsyncPager) + assert response.next_page_token == "next_page_token_value" + assert response.unreachable == ["unreachable_value"] - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).delete_channel._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set( - ( - "force", - "request_id", - ) - ) - jsonified_request.update(unset_fields) - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == "name_value" +@pytest.mark.asyncio +async def test_list_assets_async_from_dict(): + await test_list_assets_async(request_type=dict) + +def test_list_assets_field_headers(): client = LivestreamServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", ) - request = request_type(**request_init) - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name="operations/spam") - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, "request") as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, "transcode") as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - "uri": "v1/sample_method", - "method": "delete", - "query_params": pb_request, - } - transcode.return_value = transcode_result + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.ListAssetsRequest() - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) + request.parent = "parent_value" - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_assets), "__call__") as call: + call.return_value = service.ListAssetsResponse() + client.list_assets(request) - response = client.delete_channel(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 expected_params == actual_params + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] -def test_delete_channel_rest_unset_required_fields(): - transport = transports.LivestreamServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials +@pytest.mark.asyncio +async def test_list_assets_field_headers_async(): + client = LivestreamServiceAsyncClient( + credentials=async_anonymous_credentials(), ) - unset_fields = transport.delete_channel._get_unset_required_fields({}) - assert set(unset_fields) == ( - set( - ( - "force", - "requestId", - ) + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.ListAssetsRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_assets), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + service.ListAssetsResponse() ) - & set(("name",)) - ) + await client.list_assets(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_delete_channel_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_assets_flattened(): client = LivestreamServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", ) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), "request") as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name="operations/spam") - - # get arguments that satisfy an http rule for this method - sample_request = {"name": "projects/sample1/locations/sample2/channels/sample3"} - - # get truthy value for each flattened field - mock_args = dict( - name="name_value", + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_assets), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = service.ListAssetsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_assets( + parent="parent_value", ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - client.delete_channel(**mock_args) # Establish that the underlying call was 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/*/channels/*}" % client.transport._host, - args[1], - ) + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val -def test_delete_channel_rest_flattened_error(transport: str = "rest"): +def test_list_assets_flattened_error(): client = LivestreamServiceClient( credentials=ga_credentials.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_channel( - service.DeleteChannelRequest(), - name="name_value", + client.list_assets( + service.ListAssetsRequest(), + parent="parent_value", ) -def test_update_channel_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = LivestreamServiceClient( - 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_assets_flattened_async(): + client = LivestreamServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) - # Ensure method has been cached - assert client._transport.update_channel 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_assets), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = service.ListAssetsResponse() - # Replace cached 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( + service.ListAssetsResponse() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_assets( + parent="parent_value", ) - client._transport._wrapped_methods[client._transport.update_channel] = mock_rpc - - request = {} - client.update_channel(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_channel(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_channel_rest_required_fields(request_type=service.UpdateChannelRequest): - transport_class = transports.LivestreamServiceRestTransport - 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_assets_flattened_error_async(): + client = LivestreamServiceAsyncClient( + credentials=async_anonymous_credentials(), ) - # verify fields with default values are dropped - - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).update_channel._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_channel._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", + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_assets( + service.ListAssetsRequest(), + parent="parent_value", ) - ) - jsonified_request.update(unset_fields) - # verify required fields with non-default values are left alone +def test_list_assets_pager(transport_name: str = "grpc"): client = LivestreamServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport=transport_name, ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name="operations/spam") - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, "request") as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, "transcode") as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - "uri": "v1/sample_method", - "method": "patch", - "query_params": pb_request, - } - transcode_result["body"] = pb_request - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_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_channel(request) - - expected_params = [("$alt", "json;enum-encoding=int")] - actual_params = req.call_args.kwargs["params"] - assert expected_params == actual_params + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_assets), "__call__") as call: + # Set the response to a series of pages. + call.side_effect = ( + service.ListAssetsResponse( + assets=[ + resources.Asset(), + resources.Asset(), + resources.Asset(), + ], + next_page_token="abc", + ), + service.ListAssetsResponse( + assets=[], + next_page_token="def", + ), + service.ListAssetsResponse( + assets=[ + resources.Asset(), + ], + next_page_token="ghi", + ), + service.ListAssetsResponse( + assets=[ + resources.Asset(), + resources.Asset(), + ], + ), + RuntimeError, + ) -def test_update_channel_rest_unset_required_fields(): - transport = transports.LivestreamServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials - ) - - unset_fields = transport.update_channel._get_unset_required_fields({}) - assert set(unset_fields) == ( - set( - ( - "requestId", - "updateMask", - ) + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)), ) - & set(("channel",)) - ) + pager = client.list_assets(request={}, retry=retry, timeout=timeout) + assert pager._metadata == expected_metadata + assert pager._retry == retry + assert pager._timeout == timeout -def test_update_channel_rest_flattened(): + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, resources.Asset) for i in results) + + +def test_list_assets_pages(transport_name: str = "grpc"): client = LivestreamServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport=transport_name, ) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), "request") as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name="operations/spam") + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_assets), "__call__") as call: + # Set the response to a series of pages. + call.side_effect = ( + service.ListAssetsResponse( + assets=[ + resources.Asset(), + resources.Asset(), + resources.Asset(), + ], + next_page_token="abc", + ), + service.ListAssetsResponse( + assets=[], + next_page_token="def", + ), + service.ListAssetsResponse( + assets=[ + resources.Asset(), + ], + next_page_token="ghi", + ), + service.ListAssetsResponse( + assets=[ + resources.Asset(), + resources.Asset(), + ], + ), + RuntimeError, + ) + pages = list(client.list_assets(request={}).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token - # get arguments that satisfy an http rule for this method - sample_request = { - "channel": {"name": "projects/sample1/locations/sample2/channels/sample3"} - } - # get truthy value for each flattened field - mock_args = dict( - channel=resources.Channel(name="name_value"), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), +@pytest.mark.asyncio +async def test_list_assets_async_pager(): + client = LivestreamServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_assets), "__call__", new_callable=mock.AsyncMock + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + service.ListAssetsResponse( + assets=[ + resources.Asset(), + resources.Asset(), + resources.Asset(), + ], + next_page_token="abc", + ), + service.ListAssetsResponse( + assets=[], + next_page_token="def", + ), + service.ListAssetsResponse( + assets=[ + resources.Asset(), + ], + next_page_token="ghi", + ), + service.ListAssetsResponse( + assets=[ + resources.Asset(), + resources.Asset(), + ], + ), + RuntimeError, ) - mock_args.update(sample_request) + async_pager = await client.list_assets( + request={}, + ) + assert async_pager.next_page_token == "abc" + responses = [] + async for response in async_pager: # pragma: no branch + responses.append(response) - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + assert len(responses) == 6 + assert all(isinstance(i, resources.Asset) for i in responses) - client.update_channel(**mock_args) - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate( - "%s/v1/{channel.name=projects/*/locations/*/channels/*}" - % client.transport._host, - args[1], +@pytest.mark.asyncio +async def test_list_assets_async_pages(): + client = LivestreamServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_assets), "__call__", new_callable=mock.AsyncMock + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + service.ListAssetsResponse( + assets=[ + resources.Asset(), + resources.Asset(), + resources.Asset(), + ], + next_page_token="abc", + ), + service.ListAssetsResponse( + assets=[], + next_page_token="def", + ), + service.ListAssetsResponse( + assets=[ + resources.Asset(), + ], + next_page_token="ghi", + ), + service.ListAssetsResponse( + assets=[ + resources.Asset(), + resources.Asset(), + ], + ), + RuntimeError, ) + pages = [] + # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` + # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 + async for page_ in ( # pragma: no branch + await client.list_assets(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_channel_rest_flattened_error(transport: str = "rest"): +@pytest.mark.parametrize( + "request_type", + [ + service.GetPoolRequest, + dict, + ], +) +def test_get_pool(request_type, transport: str = "grpc"): client = LivestreamServiceClient( credentials=ga_credentials.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_channel( - service.UpdateChannelRequest(), - channel=resources.Channel(name="name_value"), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), - ) - + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() -def test_start_channel_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = LivestreamServiceClient( - 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.get_pool), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = resources.Pool( + name="name_value", ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.start_channel in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client._transport._wrapped_methods[client._transport.start_channel] = mock_rpc - - request = {} - client.start_channel(request) + response = client.get_pool(request) # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - # Operation methods build a cached wrapper on first rpc call - # subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() - - client.start_channel(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - - -def test_start_channel_rest_required_fields(request_type=service.StartChannelRequest): - transport_class = transports.LivestreamServiceRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads( - json_format.MessageToJson(pb_request, use_integers_for_enums=False) - ) - - # verify fields with default values are dropped - - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).start_channel._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] + request = service.GetPoolRequest() + assert args[0] == request - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).start_channel._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) + # Establish that the response is the type that we expect. + assert isinstance(response, resources.Pool) + assert response.name == "name_value" - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == "name_value" +def test_get_pool_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. client = LivestreamServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name="operations/spam") - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, "request") as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, "transcode") as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - "uri": "v1/sample_method", - "method": "post", - "query_params": pb_request, - } - transcode_result["body"] = pb_request - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - response = client.start_channel(request) - - expected_params = [("$alt", "json;enum-encoding=int")] - actual_params = req.call_args.kwargs["params"] - assert expected_params == actual_params - - -def test_start_channel_rest_unset_required_fields(): - transport = transports.LivestreamServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials + transport="grpc", ) - unset_fields = transport.start_channel._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name",))) - - -def test_start_channel_rest_flattened(): - client = LivestreamServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = service.GetPoolRequest( + name="name_value", ) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), "request") as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name="operations/spam") - - # get arguments that satisfy an http rule for this method - sample_request = {"name": "projects/sample1/locations/sample2/channels/sample3"} - - # get truthy value for each flattened field - mock_args = dict( - name="name_value", - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - client.start_channel(**mock_args) - - # Establish that the underlying call was 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/*/channels/*}:start" - % client.transport._host, - args[1], + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_pool), "__call__") as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. ) - - -def test_start_channel_rest_flattened_error(transport: str = "rest"): - client = LivestreamServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.start_channel( - service.StartChannelRequest(), + client.get_pool(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == service.GetPoolRequest( name="name_value", ) -def test_stop_channel_rest_use_cached_wrapped_rpc(): +def test_get_pool_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: client = LivestreamServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport="grpc", ) # Should wrap all calls on client creation @@ -12010,388 +12167,313 @@ def test_stop_channel_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.stop_channel in client._transport._wrapped_methods + assert client._transport.get_pool in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.Mock() mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.stop_channel] = mock_rpc - + client._transport._wrapped_methods[client._transport.get_pool] = mock_rpc request = {} - client.stop_channel(request) + client.get_pool(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.stop_channel(request) + client.get_pool(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_stop_channel_rest_required_fields(request_type=service.StopChannelRequest): - transport_class = transports.LivestreamServiceRestTransport +@pytest.mark.asyncio +async def test_get_pool_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 = LivestreamServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads( - json_format.MessageToJson(pb_request, use_integers_for_enums=False) - ) + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() - # verify fields with default values are dropped + # Ensure method has been cached + assert ( + client._client._transport.get_pool + in client._client._transport._wrapped_methods + ) - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).stop_channel._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.get_pool + ] = mock_rpc - # verify required fields with default values are now present + request = {} + await client.get_pool(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() - ).stop_channel._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) + await client.get_pool(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 = LivestreamServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + +@pytest.mark.asyncio +async def test_get_pool_async( + transport: str = "grpc_asyncio", request_type=service.GetPoolRequest +): + client = LivestreamServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, ) - request = request_type(**request_init) - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name="operations/spam") - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, "request") as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, "transcode") as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - "uri": "v1/sample_method", - "method": "post", - "query_params": pb_request, - } - transcode_result["body"] = pb_request - transcode.return_value = transcode_result + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_pool), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + resources.Pool( + name="name_value", + ) + ) + response = await client.get_pool(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) + _, args, _ = call.mock_calls[0] + request = service.GetPoolRequest() + assert args[0] == request - response = client.stop_channel(request) + # Establish that the response is the type that we expect. + assert isinstance(response, resources.Pool) + assert response.name == "name_value" - expected_params = [("$alt", "json;enum-encoding=int")] - actual_params = req.call_args.kwargs["params"] - assert expected_params == actual_params + +@pytest.mark.asyncio +async def test_get_pool_async_from_dict(): + await test_get_pool_async(request_type=dict) -def test_stop_channel_rest_unset_required_fields(): - transport = transports.LivestreamServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials +def test_get_pool_field_headers(): + client = LivestreamServiceClient( + credentials=ga_credentials.AnonymousCredentials(), ) - unset_fields = transport.stop_channel._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name",))) + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.GetPoolRequest() + request.name = "name_value" -def test_stop_channel_rest_flattened(): - client = LivestreamServiceClient( - 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.get_pool), "__call__") as call: + call.return_value = resources.Pool() + client.get_pool(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_get_pool_field_headers_async(): + client = LivestreamServiceAsyncClient( + credentials=async_anonymous_credentials(), ) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), "request") as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name="operations/spam") + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.GetPoolRequest() - # get arguments that satisfy an http rule for this method - sample_request = {"name": "projects/sample1/locations/sample2/channels/sample3"} + request.name = "name_value" - # get truthy value for each flattened field - mock_args = dict( - name="name_value", - ) - mock_args.update(sample_request) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_pool), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.Pool()) + await client.get_pool(request) - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request - client.stop_channel(**mock_args) + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] + + +def test_get_pool_flattened(): + client = LivestreamServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_pool), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = resources.Pool() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_pool( + name="name_value", + ) # Establish that the underlying call was made with the expected # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate( - "%s/v1/{name=projects/*/locations/*/channels/*}:stop" - % client.transport._host, - args[1], - ) + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val -def test_stop_channel_rest_flattened_error(transport: str = "rest"): +def test_get_pool_flattened_error(): client = LivestreamServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport=transport, ) # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.stop_channel( - service.StopChannelRequest(), + client.get_pool( + service.GetPoolRequest(), name="name_value", ) -def test_create_input_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = LivestreamServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", +@pytest.mark.asyncio +async def test_get_pool_flattened_async(): + client = LivestreamServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_pool), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = resources.Pool() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.Pool()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_pool( + name="name_value", ) - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val - # Ensure method has been cached - assert client._transport.create_input in client._transport._wrapped_methods - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. +@pytest.mark.asyncio +async def test_get_pool_flattened_error_async(): + client = LivestreamServiceAsyncClient( + 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_pool( + service.GetPoolRequest(), + name="name_value", ) - client._transport._wrapped_methods[client._transport.create_input] = mock_rpc - request = {} - client.create_input(request) - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 +@pytest.mark.parametrize( + "request_type", + [ + service.UpdatePoolRequest, + dict, + ], +) +def test_update_pool(request_type, transport: str = "grpc"): + client = LivestreamServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) - # Operation methods build a cached wrapper on first rpc call - # subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() - client.create_input(request) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.update_pool), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/spam") + response = client.update_pool(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 gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = service.UpdatePoolRequest() + assert args[0] == request + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) -def test_create_input_rest_required_fields(request_type=service.CreateInputRequest): - transport_class = transports.LivestreamServiceRestTransport - - request_init = {} - request_init["parent"] = "" - request_init["input_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 "inputId" not in jsonified_request - - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).create_input._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - assert "inputId" in jsonified_request - assert jsonified_request["inputId"] == request_init["input_id"] - - jsonified_request["parent"] = "parent_value" - jsonified_request["inputId"] = "input_id_value" - - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).create_input._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set( - ( - "input_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 "inputId" in jsonified_request - assert jsonified_request["inputId"] == "input_id_value" +def test_update_pool_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. client = LivestreamServiceClient( 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_input(request) - - expected_params = [ - ( - "inputId", - "", - ), - ("$alt", "json;enum-encoding=int"), - ] - actual_params = req.call_args.kwargs["params"] - assert expected_params == actual_params - - -def test_create_input_rest_unset_required_fields(): - transport = transports.LivestreamServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials - ) - - unset_fields = transport.create_input._get_unset_required_fields({}) - assert set(unset_fields) == ( - set( - ( - "inputId", - "requestId", - ) - ) - & set( - ( - "parent", - "input", - "inputId", - ) - ) + transport="grpc", ) - -def test_create_input_rest_flattened(): - client = LivestreamServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = service.UpdatePoolRequest( + request_id="request_id_value", ) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), "request") as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name="operations/spam") - - # get arguments that satisfy an http rule for this method - sample_request = {"parent": "projects/sample1/locations/sample2"} - - # get truthy value for each flattened field - mock_args = dict( - parent="parent_value", - input=resources.Input(name="name_value"), - input_id="input_id_value", - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - client.create_input(**mock_args) - - # Establish that the underlying call was 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/*}/inputs" % client.transport._host, - args[1], + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.update_pool), "__call__") as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. ) - - -def test_create_input_rest_flattened_error(transport: str = "rest"): - client = LivestreamServiceClient( - credentials=ga_credentials.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_input( - service.CreateInputRequest(), - parent="parent_value", - input=resources.Input(name="name_value"), - input_id="input_id_value", + client.update_pool(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == service.UpdatePoolRequest( + request_id="request_id_value", ) -def test_list_inputs_rest_use_cached_wrapped_rpc(): +def test_update_pool_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: client = LivestreamServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport="grpc", ) # Should wrap all calls on client creation @@ -12399,248 +12481,269 @@ def test_list_inputs_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.list_inputs in client._transport._wrapped_methods + assert client._transport.update_pool in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = 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_inputs] = mock_rpc - + client._transport._wrapped_methods[client._transport.update_pool] = mock_rpc request = {} - client.list_inputs(request) + client.update_pool(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.list_inputs(request) + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.update_pool(request) # Establish 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_inputs_rest_required_fields(request_type=service.ListInputsRequest): - transport_class = transports.LivestreamServiceRestTransport +@pytest.mark.asyncio +async def test_update_pool_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 = LivestreamServiceAsyncClient( + 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_pool + in client._client._transport._wrapped_methods + ) - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).list_inputs._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_pool + ] = mock_rpc - # verify required fields with default values are now present + request = {} + await client.update_pool(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_inputs._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) + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == "parent_value" + await client.update_pool(request) - client = LivestreamServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_update_pool_async( + transport: str = "grpc_asyncio", request_type=service.UpdatePoolRequest +): + client = LivestreamServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, ) - request = request_type(**request_init) - # Designate an appropriate value for the returned response. - return_value = service.ListInputsResponse() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, "request") as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, "transcode") as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - "uri": "v1/sample_method", - "method": "get", - "query_params": pb_request, - } - transcode.return_value = transcode_result + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() - response_value = Response() - response_value.status_code = 200 + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.update_pool), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + response = await client.update_pool(request) - # Convert return value to protobuf type - return_value = service.ListInputsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = service.UpdatePoolRequest() + assert args[0] == request - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) - response = client.list_inputs(request) - expected_params = [("$alt", "json;enum-encoding=int")] - actual_params = req.call_args.kwargs["params"] - assert expected_params == actual_params +@pytest.mark.asyncio +async def test_update_pool_async_from_dict(): + await test_update_pool_async(request_type=dict) -def test_list_inputs_rest_unset_required_fields(): - transport = transports.LivestreamServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials +def test_update_pool_field_headers(): + client = LivestreamServiceClient( + credentials=ga_credentials.AnonymousCredentials(), ) - unset_fields = transport.list_inputs._get_unset_required_fields({}) - assert set(unset_fields) == ( - set( - ( - "filter", - "orderBy", - "pageSize", - "pageToken", - ) - ) - & set(("parent",)) - ) + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.UpdatePoolRequest() + request.pool.name = "name_value" -def test_list_inputs_rest_flattened(): - client = LivestreamServiceClient( - 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.update_pool), "__call__") as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.update_pool(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", + "pool.name=name_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_update_pool_field_headers_async(): + client = LivestreamServiceAsyncClient( + credentials=async_anonymous_credentials(), ) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), "request") as req: - # Designate an appropriate value for the returned response. - return_value = service.ListInputsResponse() + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.UpdatePoolRequest() - # get arguments that satisfy an http rule for this method - sample_request = {"parent": "projects/sample1/locations/sample2"} + request.pool.name = "name_value" - # get truthy value for each flattened field - mock_args = dict( - parent="parent_value", + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.update_pool), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/op") ) - mock_args.update(sample_request) + await client.update_pool(request) - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = service.ListInputsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request - client.list_inputs(**mock_args) + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "pool.name=name_value", + ) in kw["metadata"] + + +def test_update_pool_flattened(): + client = LivestreamServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.update_pool), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/op") + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_pool( + pool=resources.Pool(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=projects/*/locations/*}/inputs" % client.transport._host, - args[1], - ) + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].pool + mock_val = resources.Pool(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_inputs_rest_flattened_error(transport: str = "rest"): +def test_update_pool_flattened_error(): client = LivestreamServiceClient( credentials=ga_credentials.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_inputs( - service.ListInputsRequest(), - parent="parent_value", + client.update_pool( + service.UpdatePoolRequest(), + pool=resources.Pool(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) -def test_list_inputs_rest_pager(transport: str = "rest"): - client = LivestreamServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, +@pytest.mark.asyncio +async def test_update_pool_flattened_async(): + client = LivestreamServiceAsyncClient( + credentials=async_anonymous_credentials(), ) - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, "request") as req: - # TODO(kbandes): remove this mock unless there's a good reason for it. - # with mock.patch.object(path_template, 'transcode') as transcode: - # Set the response as a series of pages - response = ( - service.ListInputsResponse( - inputs=[ - resources.Input(), - resources.Input(), - resources.Input(), - ], - next_page_token="abc", - ), - service.ListInputsResponse( - inputs=[], - next_page_token="def", - ), - service.ListInputsResponse( - inputs=[ - resources.Input(), - ], - next_page_token="ghi", - ), - service.ListInputsResponse( - inputs=[ - resources.Input(), - resources.Input(), - ], - ), - ) - # Two responses for two calls - response = response + response + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.update_pool), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/op") - # Wrap the values into proper Response objs - response = tuple(service.ListInputsResponse.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 + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_pool( + pool=resources.Pool(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) - sample_request = {"parent": "projects/sample1/locations/sample2"} + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].pool + mock_val = resources.Pool(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 - pager = client.list_inputs(request=sample_request) - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, resources.Input) for i in results) +@pytest.mark.asyncio +async def test_update_pool_flattened_error_async(): + client = LivestreamServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) - pages = list(client.list_inputs(request=sample_request).pages) - for page_, token in zip(pages, ["abc", "def", "ghi", ""]): - assert page_.raw_page.next_page_token == token + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.update_pool( + service.UpdatePoolRequest(), + pool=resources.Pool(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) -def test_get_input_rest_use_cached_wrapped_rpc(): +def test_create_channel_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -12654,33 +12757,38 @@ def test_get_input_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.get_input in client._transport._wrapped_methods + assert client._transport.create_channel_ in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = 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_input] = mock_rpc + client._transport._wrapped_methods[client._transport.create_channel_] = mock_rpc request = {} - client.get_input(request) + client.create_channel(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.get_input(request) + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.create_channel(request) # Establish 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_input_rest_required_fields(request_type=service.GetInputRequest): +def test_create_channel_rest_required_fields(request_type=service.CreateChannelRequest): transport_class = transports.LivestreamServiceRestTransport request_init = {} - request_init["name"] = "" + request_init["parent"] = "" + request_init["channel_id"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -12688,24 +12796,37 @@ def test_get_input_rest_required_fields(request_type=service.GetInputRequest): ) # verify fields with default values are dropped + assert "channelId" not in jsonified_request unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).get_input._get_unset_required_fields(jsonified_request) + ).create_channel_._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present + assert "channelId" in jsonified_request + assert jsonified_request["channelId"] == request_init["channel_id"] - jsonified_request["name"] = "name_value" + jsonified_request["parent"] = "parent_value" + jsonified_request["channelId"] = "channel_id_value" unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).get_input._get_unset_required_fields(jsonified_request) + ).create_channel_._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "channel_id", + "request_id", + ) + ) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == "name_value" + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + assert "channelId" in jsonified_request + assert jsonified_request["channelId"] == "channel_id_value" client = LivestreamServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -12714,7 +12835,7 @@ def test_get_input_rest_required_fields(request_type=service.GetInputRequest): request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = resources.Input() + 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 @@ -12726,39 +12847,57 @@ def test_get_input_rest_required_fields(request_type=service.GetInputRequest): pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "get", + "method": "post", "query_params": pb_request, } + transcode_result["body"] = pb_request transcode.return_value = transcode_result response_value = Response() response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = resources.Input.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_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_input(request) + response = client.create_channel(request) - expected_params = [("$alt", "json;enum-encoding=int")] + expected_params = [ + ( + "channelId", + "", + ), + ("$alt", "json;enum-encoding=int"), + ] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_get_input_rest_unset_required_fields(): +def test_create_channel_rest_unset_required_fields(): transport = transports.LivestreamServiceRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.get_input._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name",))) + unset_fields = transport.create_channel_._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "channelId", + "requestId", + ) + ) + & set( + ( + "parent", + "channel", + "channelId", + ) + ) + ) -def test_get_input_rest_flattened(): +def test_create_channel_rest_flattened(): client = LivestreamServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -12767,40 +12906,40 @@ def test_get_input_rest_flattened(): # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = resources.Input() + 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/inputs/sample3"} + sample_request = {"parent": "projects/sample1/locations/sample2"} # get truthy value for each flattened field mock_args = dict( - name="name_value", + parent="parent_value", + channel=resources.Channel(name="name_value"), + channel_id="channel_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 = resources.Input.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = 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_input(**mock_args) + client.create_channel(**mock_args) # Establish that the underlying call was 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/*/inputs/*}" % client.transport._host, + "%s/v1/{parent=projects/*/locations/*}/channels" % client.transport._host, args[1], ) -def test_get_input_rest_flattened_error(transport: str = "rest"): +def test_create_channel_rest_flattened_error(transport: str = "rest"): client = LivestreamServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -12809,13 +12948,15 @@ def test_get_input_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_input( - service.GetInputRequest(), - name="name_value", + client.create_channel( + service.CreateChannelRequest(), + parent="parent_value", + channel=resources.Channel(name="name_value"), + channel_id="channel_id_value", ) -def test_delete_input_rest_use_cached_wrapped_rpc(): +def test_list_channels_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -12829,37 +12970,33 @@ def test_delete_input_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.delete_input in client._transport._wrapped_methods + assert client._transport.list_channels in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = 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_input] = mock_rpc + client._transport._wrapped_methods[client._transport.list_channels] = mock_rpc request = {} - client.delete_input(request) + client.list_channels(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_input(request) + client.list_channels(request) # Establish 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_input_rest_required_fields(request_type=service.DeleteInputRequest): +def test_list_channels_rest_required_fields(request_type=service.ListChannelsRequest): transport_class = transports.LivestreamServiceRestTransport request_init = {} - request_init["name"] = "" + request_init["parent"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -12870,23 +13007,30 @@ def test_delete_input_rest_required_fields(request_type=service.DeleteInputReque unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).delete_input._get_unset_required_fields(jsonified_request) + ).list_channels._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() - ).delete_input._get_unset_required_fields(jsonified_request) + ).list_channels._get_unset_required_fields(jsonified_request) # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("request_id",)) + assert not set(unset_fields) - set( + ( + "filter", + "order_by", + "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 = LivestreamServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -12895,7 +13039,7 @@ def test_delete_input_rest_required_fields(request_type=service.DeleteInputReque request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name="operations/spam") + return_value = service.ListChannelsResponse() # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values @@ -12907,36 +13051,49 @@ def test_delete_input_rest_required_fields(request_type=service.DeleteInputReque 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 = service.ListChannelsResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_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_input(request) + response = client.list_channels(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_delete_input_rest_unset_required_fields(): +def test_list_channels_rest_unset_required_fields(): transport = transports.LivestreamServiceRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.delete_input._get_unset_required_fields({}) - assert set(unset_fields) == (set(("requestId",)) & set(("name",))) + unset_fields = transport.list_channels._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "filter", + "orderBy", + "pageSize", + "pageToken", + ) + ) + & set(("parent",)) + ) -def test_delete_input_rest_flattened(): +def test_list_channels_rest_flattened(): client = LivestreamServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -12945,38 +13102,40 @@ def test_delete_input_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 = service.ListChannelsResponse() # get arguments that satisfy an http rule for this method - sample_request = {"name": "projects/sample1/locations/sample2/inputs/sample3"} + 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) # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 + # Convert return value to protobuf type + return_value = service.ListChannelsResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = 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_input(**mock_args) + client.list_channels(**mock_args) # Establish that the underlying call was 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/*/inputs/*}" % client.transport._host, + "%s/v1/{parent=projects/*/locations/*}/channels" % client.transport._host, args[1], ) -def test_delete_input_rest_flattened_error(transport: str = "rest"): +def test_list_channels_rest_flattened_error(transport: str = "rest"): client = LivestreamServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -12985,56 +13144,114 @@ def test_delete_input_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_input( - service.DeleteInputRequest(), - name="name_value", - ) - - -def test_update_input_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = LivestreamServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should 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_input in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. + client.list_channels( + service.ListChannelsRequest(), + parent="parent_value", ) - client._transport._wrapped_methods[client._transport.update_input] = mock_rpc - request = {} - client.update_input(request) - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 +def test_list_channels_rest_pager(transport: str = "rest"): + client = LivestreamServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) - # Operation methods build a cached wrapper on first rpc call - # subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # TODO(kbandes): remove this mock unless there's a good reason for it. + # with mock.patch.object(path_template, 'transcode') as transcode: + # Set the response as a series of pages + response = ( + service.ListChannelsResponse( + channels=[ + resources.Channel(), + resources.Channel(), + resources.Channel(), + ], + next_page_token="abc", + ), + service.ListChannelsResponse( + channels=[], + next_page_token="def", + ), + service.ListChannelsResponse( + channels=[ + resources.Channel(), + ], + next_page_token="ghi", + ), + service.ListChannelsResponse( + channels=[ + resources.Channel(), + resources.Channel(), + ], + ), + ) + # Two responses for two calls + response = response + response - client.update_input(request) + # Wrap the values into proper Response objs + response = tuple(service.ListChannelsResponse.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_channels(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, resources.Channel) for i in results) + + pages = list(client.list_channels(request=sample_request).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +def test_get_channel_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = LivestreamServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should 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_channel in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_channel] = mock_rpc + + request = {} + client.get_channel(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_channel(request) # Establish 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_input_rest_required_fields(request_type=service.UpdateInputRequest): +def test_get_channel_rest_required_fields(request_type=service.GetChannelRequest): transport_class = transports.LivestreamServiceRestTransport request_init = {} + request_init["name"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -13045,24 +13262,21 @@ def test_update_input_rest_required_fields(request_type=service.UpdateInputReque unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).update_input._get_unset_required_fields(jsonified_request) + ).get_channel._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_input._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_channel._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 = LivestreamServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -13071,7 +13285,7 @@ def test_update_input_rest_required_fields(request_type=service.UpdateInputReque request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name="operations/spam") + return_value = resources.Channel() # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values @@ -13083,45 +13297,39 @@ def test_update_input_rest_required_fields(request_type=service.UpdateInputReque 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 = resources.Channel.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_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_input(request) + response = client.get_channel(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_update_input_rest_unset_required_fields(): +def test_get_channel_rest_unset_required_fields(): transport = transports.LivestreamServiceRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.update_input._get_unset_required_fields({}) - assert set(unset_fields) == ( - set( - ( - "requestId", - "updateMask", - ) - ) - & set(("input",)) - ) + unset_fields = transport.get_channel._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) -def test_update_input_rest_flattened(): +def test_get_channel_rest_flattened(): client = LivestreamServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -13130,42 +13338,40 @@ def test_update_input_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 = resources.Channel() # get arguments that satisfy an http rule for this method - sample_request = { - "input": {"name": "projects/sample1/locations/sample2/inputs/sample3"} - } + sample_request = {"name": "projects/sample1/locations/sample2/channels/sample3"} # get truthy value for each flattened field mock_args = dict( - input=resources.Input(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 = resources.Channel.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = 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_input(**mock_args) + client.get_channel(**mock_args) # Establish that the underlying call was made with the expected # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] assert path_template.validate( - "%s/v1/{input.name=projects/*/locations/*/inputs/*}" - % client.transport._host, + "%s/v1/{name=projects/*/locations/*/channels/*}" % client.transport._host, args[1], ) -def test_update_input_rest_flattened_error(transport: str = "rest"): +def test_get_channel_rest_flattened_error(transport: str = "rest"): client = LivestreamServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -13174,14 +13380,13 @@ def test_update_input_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_input( - service.UpdateInputRequest(), - input=resources.Input(name="name_value"), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + client.get_channel( + service.GetChannelRequest(), + name="name_value", ) -def test_create_event_rest_use_cached_wrapped_rpc(): +def test_delete_channel_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -13195,34 +13400,37 @@ def test_create_event_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.create_event in client._transport._wrapped_methods + assert client._transport.delete_channel in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = 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_event] = mock_rpc + client._transport._wrapped_methods[client._transport.delete_channel] = mock_rpc request = {} - client.create_event(request) + client.delete_channel(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.create_event(request) + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.delete_channel(request) # Establish 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_event_rest_required_fields(request_type=service.CreateEventRequest): +def test_delete_channel_rest_required_fields(request_type=service.DeleteChannelRequest): transport_class = transports.LivestreamServiceRestTransport request_init = {} - request_init["parent"] = "" - request_init["event_id"] = "" + request_init["name"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -13230,37 +13438,31 @@ def test_create_event_rest_required_fields(request_type=service.CreateEventReque ) # verify fields with default values are dropped - assert "eventId" not in jsonified_request unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).create_event._get_unset_required_fields(jsonified_request) + ).delete_channel._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present - assert "eventId" in jsonified_request - assert jsonified_request["eventId"] == request_init["event_id"] - jsonified_request["parent"] = "parent_value" - jsonified_request["eventId"] = "event_id_value" + jsonified_request["name"] = "name_value" unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).create_event._get_unset_required_fields(jsonified_request) + ).delete_channel._get_unset_required_fields(jsonified_request) # Check that path parameters and body parameters are not mixing in. assert not set(unset_fields) - set( ( - "event_id", + "force", "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 "eventId" in jsonified_request - assert jsonified_request["eventId"] == "event_id_value" + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" client = LivestreamServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -13269,7 +13471,7 @@ def test_create_event_rest_required_fields(request_type=service.CreateEventReque request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = resources.Event() + 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 @@ -13281,60 +13483,44 @@ def test_create_event_rest_required_fields(request_type=service.CreateEventReque pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "post", + "method": "delete", "query_params": pb_request, } - transcode_result["body"] = pb_request transcode.return_value = transcode_result response_value = Response() response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = resources.Event.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_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_event(request) + response = client.delete_channel(request) - expected_params = [ - ( - "eventId", - "", - ), - ("$alt", "json;enum-encoding=int"), - ] + expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_create_event_rest_unset_required_fields(): +def test_delete_channel_rest_unset_required_fields(): transport = transports.LivestreamServiceRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.create_event._get_unset_required_fields({}) + unset_fields = transport.delete_channel._get_unset_required_fields({}) assert set(unset_fields) == ( set( ( - "eventId", + "force", "requestId", ) ) - & set( - ( - "parent", - "event", - "eventId", - ) - ) + & set(("name",)) ) -def test_create_event_rest_flattened(): +def test_delete_channel_rest_flattened(): client = LivestreamServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -13343,45 +13529,38 @@ def test_create_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 = resources.Event() + 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/channels/sample3" - } + sample_request = {"name": "projects/sample1/locations/sample2/channels/sample3"} # get truthy value for each flattened field mock_args = dict( - parent="parent_value", - event=resources.Event(name="name_value"), - event_id="event_id_value", + name="name_value", ) mock_args.update(sample_request) # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 - # Convert return value to protobuf type - return_value = resources.Event.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = 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_event(**mock_args) + client.delete_channel(**mock_args) # Establish that the underlying call was 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/*/channels/*}/events" - % client.transport._host, + "%s/v1/{name=projects/*/locations/*/channels/*}" % client.transport._host, args[1], ) -def test_create_event_rest_flattened_error(transport: str = "rest"): +def test_delete_channel_rest_flattened_error(transport: str = "rest"): client = LivestreamServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -13390,15 +13569,13 @@ def test_create_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.create_event( - service.CreateEventRequest(), - parent="parent_value", - event=resources.Event(name="name_value"), - event_id="event_id_value", + client.delete_channel( + service.DeleteChannelRequest(), + name="name_value", ) -def test_list_events_rest_use_cached_wrapped_rpc(): +def test_update_channel_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -13412,33 +13589,36 @@ def test_list_events_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.list_events in client._transport._wrapped_methods + assert client._transport.update_channel in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = 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_events] = mock_rpc + client._transport._wrapped_methods[client._transport.update_channel] = mock_rpc request = {} - client.list_events(request) + client.update_channel(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.list_events(request) + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.update_channel(request) # Establish 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_events_rest_required_fields(request_type=service.ListEventsRequest): +def test_update_channel_rest_required_fields(request_type=service.UpdateChannelRequest): transport_class = transports.LivestreamServiceRestTransport request_init = {} - request_init["parent"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -13449,30 +13629,24 @@ def test_list_events_rest_required_fields(request_type=service.ListEventsRequest unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).list_events._get_unset_required_fields(jsonified_request) + ).update_channel._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_events._get_unset_required_fields(jsonified_request) + ).update_channel._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", + "request_id", + "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 = LivestreamServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -13481,7 +13655,7 @@ def test_list_events_rest_required_fields(request_type=service.ListEventsRequest request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = service.ListEventsResponse() + 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 @@ -13493,49 +13667,45 @@ def test_list_events_rest_required_fields(request_type=service.ListEventsRequest 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 = service.ListEventsResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_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_events(request) + response = client.update_channel(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_list_events_rest_unset_required_fields(): +def test_update_channel_rest_unset_required_fields(): transport = transports.LivestreamServiceRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.list_events._get_unset_required_fields({}) + unset_fields = transport.update_channel._get_unset_required_fields({}) assert set(unset_fields) == ( set( ( - "filter", - "orderBy", - "pageSize", - "pageToken", + "requestId", + "updateMask", ) ) - & set(("parent",)) + & set(("channel",)) ) -def test_list_events_rest_flattened(): +def test_update_channel_rest_flattened(): client = LivestreamServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -13544,43 +13714,42 @@ def test_list_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 = service.ListEventsResponse() + 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/channels/sample3" + "channel": {"name": "projects/sample1/locations/sample2/channels/sample3"} } # get truthy value for each flattened field mock_args = dict( - parent="parent_value", + channel=resources.Channel(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 = service.ListEventsResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = 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_events(**mock_args) + client.update_channel(**mock_args) # Establish that the underlying call was 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/*/channels/*}/events" + "%s/v1/{channel.name=projects/*/locations/*/channels/*}" % client.transport._host, args[1], ) -def test_list_events_rest_flattened_error(transport: str = "rest"): +def test_update_channel_rest_flattened_error(transport: str = "rest"): client = LivestreamServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -13589,76 +13758,14 @@ def test_list_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_events( - service.ListEventsRequest(), - parent="parent_value", - ) - - -def test_list_events_rest_pager(transport: str = "rest"): - client = LivestreamServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, "request") as req: - # TODO(kbandes): remove this mock unless there's a good reason for it. - # with mock.patch.object(path_template, 'transcode') as transcode: - # Set the response as a series of pages - response = ( - service.ListEventsResponse( - events=[ - resources.Event(), - resources.Event(), - resources.Event(), - ], - next_page_token="abc", - ), - service.ListEventsResponse( - events=[], - next_page_token="def", - ), - service.ListEventsResponse( - events=[ - resources.Event(), - ], - next_page_token="ghi", - ), - service.ListEventsResponse( - events=[ - resources.Event(), - resources.Event(), - ], - ), + client.update_channel( + service.UpdateChannelRequest(), + channel=resources.Channel(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(service.ListEventsResponse.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/channels/sample3" - } - - pager = client.list_events(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, resources.Event) for i in results) - - pages = list(client.list_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_event_rest_use_cached_wrapped_rpc(): +def test_start_channel_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -13672,29 +13779,33 @@ def test_get_event_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.get_event in client._transport._wrapped_methods + assert client._transport.start_channel in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = 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_event] = mock_rpc + client._transport._wrapped_methods[client._transport.start_channel] = mock_rpc request = {} - client.get_event(request) + client.start_channel(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.get_event(request) + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.start_channel(request) # Establish 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_event_rest_required_fields(request_type=service.GetEventRequest): +def test_start_channel_rest_required_fields(request_type=service.StartChannelRequest): transport_class = transports.LivestreamServiceRestTransport request_init = {} @@ -13709,7 +13820,7 @@ def test_get_event_rest_required_fields(request_type=service.GetEventRequest): unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).get_event._get_unset_required_fields(jsonified_request) + ).start_channel._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present @@ -13718,7 +13829,7 @@ def test_get_event_rest_required_fields(request_type=service.GetEventRequest): unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).get_event._get_unset_required_fields(jsonified_request) + ).start_channel._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone @@ -13732,7 +13843,7 @@ def test_get_event_rest_required_fields(request_type=service.GetEventRequest): request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = resources.Event() + 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 @@ -13744,39 +13855,37 @@ def test_get_event_rest_required_fields(request_type=service.GetEventRequest): pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "get", + "method": "post", "query_params": pb_request, } + transcode_result["body"] = pb_request transcode.return_value = transcode_result response_value = Response() response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = resources.Event.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_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_event(request) + response = client.start_channel(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_get_event_rest_unset_required_fields(): +def test_start_channel_rest_unset_required_fields(): transport = transports.LivestreamServiceRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.get_event._get_unset_required_fields({}) + unset_fields = transport.start_channel._get_unset_required_fields({}) assert set(unset_fields) == (set(()) & set(("name",))) -def test_get_event_rest_flattened(): +def test_start_channel_rest_flattened(): client = LivestreamServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -13785,12 +13894,10 @@ def test_get_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 = resources.Event() + 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/channels/sample3/events/sample4" - } + sample_request = {"name": "projects/sample1/locations/sample2/channels/sample3"} # get truthy value for each flattened field mock_args = dict( @@ -13801,27 +13908,25 @@ def test_get_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 = resources.Event.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = 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_event(**mock_args) + client.start_channel(**mock_args) # Establish that the underlying call was 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/*/channels/*/events/*}" + "%s/v1/{name=projects/*/locations/*/channels/*}:start" % client.transport._host, args[1], ) -def test_get_event_rest_flattened_error(transport: str = "rest"): +def test_start_channel_rest_flattened_error(transport: str = "rest"): client = LivestreamServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -13830,13 +13935,13 @@ def test_get_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_event( - service.GetEventRequest(), + client.start_channel( + service.StartChannelRequest(), name="name_value", ) -def test_delete_event_rest_use_cached_wrapped_rpc(): +def test_stop_channel_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -13850,29 +13955,33 @@ def test_delete_event_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.delete_event in client._transport._wrapped_methods + assert client._transport.stop_channel in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = 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_event] = mock_rpc + client._transport._wrapped_methods[client._transport.stop_channel] = mock_rpc request = {} - client.delete_event(request) + client.stop_channel(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.delete_event(request) + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.stop_channel(request) # Establish 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_event_rest_required_fields(request_type=service.DeleteEventRequest): +def test_stop_channel_rest_required_fields(request_type=service.StopChannelRequest): transport_class = transports.LivestreamServiceRestTransport request_init = {} @@ -13887,7 +13996,7 @@ def test_delete_event_rest_required_fields(request_type=service.DeleteEventReque unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).delete_event._get_unset_required_fields(jsonified_request) + ).stop_channel._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present @@ -13896,9 +14005,7 @@ def test_delete_event_rest_required_fields(request_type=service.DeleteEventReque unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).delete_event._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",)) + ).stop_channel._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone @@ -13912,7 +14019,7 @@ def test_delete_event_rest_required_fields(request_type=service.DeleteEventReque request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = None + 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 @@ -13924,36 +14031,37 @@ def test_delete_event_rest_required_fields(request_type=service.DeleteEventReque 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 = "" + json_return_value = json_format.MessageToJson(return_value) response_value._content = json_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_event(request) + response = client.stop_channel(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_delete_event_rest_unset_required_fields(): +def test_stop_channel_rest_unset_required_fields(): transport = transports.LivestreamServiceRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.delete_event._get_unset_required_fields({}) - assert set(unset_fields) == (set(("requestId",)) & set(("name",))) + unset_fields = transport.stop_channel._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) -def test_delete_event_rest_flattened(): +def test_stop_channel_rest_flattened(): client = LivestreamServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -13962,12 +14070,10 @@ def test_delete_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 = None + 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/channels/sample3/events/sample4" - } + sample_request = {"name": "projects/sample1/locations/sample2/channels/sample3"} # get truthy value for each flattened field mock_args = dict( @@ -13978,25 +14084,25 @@ def test_delete_event_rest_flattened(): # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 - json_return_value = "" + json_return_value = json_format.MessageToJson(return_value) response_value._content = 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_event(**mock_args) + client.stop_channel(**mock_args) # Establish that the underlying call was 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/*/channels/*/events/*}" + "%s/v1/{name=projects/*/locations/*/channels/*}:stop" % client.transport._host, args[1], ) -def test_delete_event_rest_flattened_error(transport: str = "rest"): +def test_stop_channel_rest_flattened_error(transport: str = "rest"): client = LivestreamServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -14005,13 +14111,13 @@ def test_delete_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.delete_event( - service.DeleteEventRequest(), + client.stop_channel( + service.StopChannelRequest(), name="name_value", ) -def test_list_clips_rest_use_cached_wrapped_rpc(): +def test_create_input_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -14025,33 +14131,38 @@ def test_list_clips_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.list_clips in client._transport._wrapped_methods + assert client._transport.create_input in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = 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_clips] = mock_rpc + client._transport._wrapped_methods[client._transport.create_input] = mock_rpc request = {} - client.list_clips(request) + client.create_input(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.list_clips(request) + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.create_input(request) # Establish 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_clips_rest_required_fields(request_type=service.ListClipsRequest): +def test_create_input_rest_required_fields(request_type=service.CreateInputRequest): transport_class = transports.LivestreamServiceRestTransport request_init = {} request_init["parent"] = "" + request_init["input_id"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -14059,26 +14170,28 @@ def test_list_clips_rest_required_fields(request_type=service.ListClipsRequest): ) # verify fields with default values are dropped + assert "inputId" not in jsonified_request unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).list_clips._get_unset_required_fields(jsonified_request) + ).create_input._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present + assert "inputId" in jsonified_request + assert jsonified_request["inputId"] == request_init["input_id"] jsonified_request["parent"] = "parent_value" + jsonified_request["inputId"] = "input_id_value" unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).list_clips._get_unset_required_fields(jsonified_request) + ).create_input._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", + "input_id", + "request_id", ) ) jsonified_request.update(unset_fields) @@ -14086,6 +14199,8 @@ def test_list_clips_rest_required_fields(request_type=service.ListClipsRequest): # verify required fields with non-default values are left alone assert "parent" in jsonified_request assert jsonified_request["parent"] == "parent_value" + assert "inputId" in jsonified_request + assert jsonified_request["inputId"] == "input_id_value" client = LivestreamServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -14094,7 +14209,7 @@ def test_list_clips_rest_required_fields(request_type=service.ListClipsRequest): request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = service.ListClipsResponse() + 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 @@ -14106,49 +14221,57 @@ def test_list_clips_rest_required_fields(request_type=service.ListClipsRequest): 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 = service.ListClipsResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_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_clips(request) + response = client.create_input(request) - expected_params = [("$alt", "json;enum-encoding=int")] + expected_params = [ + ( + "inputId", + "", + ), + ("$alt", "json;enum-encoding=int"), + ] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_list_clips_rest_unset_required_fields(): +def test_create_input_rest_unset_required_fields(): transport = transports.LivestreamServiceRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.list_clips._get_unset_required_fields({}) + unset_fields = transport.create_input._get_unset_required_fields({}) assert set(unset_fields) == ( set( ( - "filter", - "orderBy", - "pageSize", - "pageToken", + "inputId", + "requestId", + ) + ) + & set( + ( + "parent", + "input", + "inputId", ) ) - & set(("parent",)) ) -def test_list_clips_rest_flattened(): +def test_create_input_rest_flattened(): client = LivestreamServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -14157,43 +14280,40 @@ def test_list_clips_rest_flattened(): # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = service.ListClipsResponse() + 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/channels/sample3" - } + sample_request = {"parent": "projects/sample1/locations/sample2"} # get truthy value for each flattened field mock_args = dict( parent="parent_value", + input=resources.Input(name="name_value"), + input_id="input_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 = service.ListClipsResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = 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_clips(**mock_args) + client.create_input(**mock_args) # Establish that the underlying call was 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/*/channels/*}/clips" - % client.transport._host, + "%s/v1/{parent=projects/*/locations/*}/inputs" % client.transport._host, args[1], ) -def test_list_clips_rest_flattened_error(transport: str = "rest"): +def test_create_input_rest_flattened_error(transport: str = "rest"): client = LivestreamServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -14202,76 +14322,15 @@ def test_list_clips_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_clips( - service.ListClipsRequest(), + client.create_input( + service.CreateInputRequest(), parent="parent_value", + input=resources.Input(name="name_value"), + input_id="input_id_value", ) -def test_list_clips_rest_pager(transport: str = "rest"): - client = LivestreamServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, "request") as req: - # TODO(kbandes): remove this mock unless there's a good reason for it. - # with mock.patch.object(path_template, 'transcode') as transcode: - # Set the response as a series of pages - response = ( - service.ListClipsResponse( - clips=[ - resources.Clip(), - resources.Clip(), - resources.Clip(), - ], - next_page_token="abc", - ), - service.ListClipsResponse( - clips=[], - next_page_token="def", - ), - service.ListClipsResponse( - clips=[ - resources.Clip(), - ], - next_page_token="ghi", - ), - service.ListClipsResponse( - clips=[ - resources.Clip(), - resources.Clip(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(service.ListClipsResponse.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/channels/sample3" - } - - pager = client.list_clips(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, resources.Clip) for i in results) - - pages = list(client.list_clips(request=sample_request).pages) - for page_, token in zip(pages, ["abc", "def", "ghi", ""]): - assert page_.raw_page.next_page_token == token - - -def test_get_clip_rest_use_cached_wrapped_rpc(): +def test_list_inputs_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -14285,33 +14344,33 @@ def test_get_clip_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.get_clip in client._transport._wrapped_methods + assert client._transport.list_inputs in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = 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_clip] = mock_rpc + client._transport._wrapped_methods[client._transport.list_inputs] = mock_rpc request = {} - client.get_clip(request) + client.list_inputs(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.get_clip(request) + client.list_inputs(request) # Establish 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_clip_rest_required_fields(request_type=service.GetClipRequest): +def test_list_inputs_rest_required_fields(request_type=service.ListInputsRequest): transport_class = transports.LivestreamServiceRestTransport request_init = {} - request_init["name"] = "" + request_init["parent"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -14322,21 +14381,30 @@ def test_get_clip_rest_required_fields(request_type=service.GetClipRequest): unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).get_clip._get_unset_required_fields(jsonified_request) + ).list_inputs._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_clip._get_unset_required_fields(jsonified_request) + ).list_inputs._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 "name" in jsonified_request - assert jsonified_request["name"] == "name_value" + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" client = LivestreamServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -14345,7 +14413,7 @@ def test_get_clip_rest_required_fields(request_type=service.GetClipRequest): request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = resources.Clip() + return_value = service.ListInputsResponse() # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values @@ -14366,30 +14434,40 @@ def test_get_clip_rest_required_fields(request_type=service.GetClipRequest): response_value.status_code = 200 # Convert return value to protobuf type - return_value = resources.Clip.pb(return_value) + return_value = service.ListInputsResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_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_clip(request) + response = client.list_inputs(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_get_clip_rest_unset_required_fields(): +def test_list_inputs_rest_unset_required_fields(): transport = transports.LivestreamServiceRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.get_clip._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name",))) + unset_fields = transport.list_inputs._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "filter", + "orderBy", + "pageSize", + "pageToken", + ) + ) + & set(("parent",)) + ) -def test_get_clip_rest_flattened(): +def test_list_inputs_rest_flattened(): client = LivestreamServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -14398,16 +14476,14 @@ def test_get_clip_rest_flattened(): # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = resources.Clip() + return_value = service.ListInputsResponse() # get arguments that satisfy an http rule for this method - sample_request = { - "name": "projects/sample1/locations/sample2/channels/sample3/clips/sample4" - } + 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) @@ -14415,26 +14491,25 @@ def test_get_clip_rest_flattened(): response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = resources.Clip.pb(return_value) + return_value = service.ListInputsResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = 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_clip(**mock_args) + client.list_inputs(**mock_args) # Establish that the underlying call was 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/*/channels/*/clips/*}" - % client.transport._host, + "%s/v1/{parent=projects/*/locations/*}/inputs" % client.transport._host, args[1], ) -def test_get_clip_rest_flattened_error(transport: str = "rest"): +def test_list_inputs_rest_flattened_error(transport: str = "rest"): client = LivestreamServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -14443,58 +14518,114 @@ def test_get_clip_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_clip( - service.GetClipRequest(), - name="name_value", - ) - - -def test_create_clip_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = LivestreamServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + client.list_inputs( + service.ListInputsRequest(), + parent="parent_value", ) - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.create_clip in client._transport._wrapped_methods - # Replace cached wrapped function with mock - mock_rpc = 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_clip] = mock_rpc +def test_list_inputs_rest_pager(transport: str = "rest"): + client = LivestreamServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) - request = {} - client.create_clip(request) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # TODO(kbandes): remove this mock unless there's a good reason for it. + # with mock.patch.object(path_template, 'transcode') as transcode: + # Set the response as a series of pages + response = ( + service.ListInputsResponse( + inputs=[ + resources.Input(), + resources.Input(), + resources.Input(), + ], + next_page_token="abc", + ), + service.ListInputsResponse( + inputs=[], + next_page_token="def", + ), + service.ListInputsResponse( + inputs=[ + resources.Input(), + ], + next_page_token="ghi", + ), + service.ListInputsResponse( + inputs=[ + resources.Input(), + resources.Input(), + ], + ), + ) + # Two responses for two calls + response = response + response - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 + # Wrap the values into proper Response objs + response = tuple(service.ListInputsResponse.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 - # Operation methods build a cached wrapper on first rpc call - # subsequent calls should use the cached wrapper + sample_request = {"parent": "projects/sample1/locations/sample2"} + + pager = client.list_inputs(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, resources.Input) for i in results) + + pages = list(client.list_inputs(request=sample_request).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +def test_get_input_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = LivestreamServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 wrapper_fn.reset_mock() - client.create_clip(request) + # Ensure method has been cached + assert client._transport.get_input in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_input] = mock_rpc + + request = {} + client.get_input(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_input(request) # Establish 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_clip_rest_required_fields(request_type=service.CreateClipRequest): +def test_get_input_rest_required_fields(request_type=service.GetInputRequest): transport_class = transports.LivestreamServiceRestTransport request_init = {} - request_init["parent"] = "" - request_init["clip_id"] = "" + request_init["name"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -14502,37 +14633,24 @@ def test_create_clip_rest_required_fields(request_type=service.CreateClipRequest ) # verify fields with default values are dropped - assert "clipId" not in jsonified_request unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).create_clip._get_unset_required_fields(jsonified_request) + ).get_input._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present - assert "clipId" in jsonified_request - assert jsonified_request["clipId"] == request_init["clip_id"] - jsonified_request["parent"] = "parent_value" - jsonified_request["clipId"] = "clip_id_value" + jsonified_request["name"] = "name_value" unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).create_clip._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set( - ( - "clip_id", - "request_id", - ) - ) + ).get_input._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 "clipId" in jsonified_request - assert jsonified_request["clipId"] == "clip_id_value" + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" client = LivestreamServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -14541,7 +14659,7 @@ def test_create_clip_rest_required_fields(request_type=service.CreateClipRequest request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name="operations/spam") + return_value = resources.Input() # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values @@ -14553,57 +14671,39 @@ def test_create_clip_rest_required_fields(request_type=service.CreateClipRequest pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "post", + "method": "get", "query_params": pb_request, } - transcode_result["body"] = pb_request transcode.return_value = transcode_result response_value = Response() response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = resources.Input.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_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_clip(request) + response = client.get_input(request) - expected_params = [ - ( - "clipId", - "", - ), - ("$alt", "json;enum-encoding=int"), - ] + expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_create_clip_rest_unset_required_fields(): +def test_get_input_rest_unset_required_fields(): transport = transports.LivestreamServiceRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.create_clip._get_unset_required_fields({}) - assert set(unset_fields) == ( - set( - ( - "clipId", - "requestId", - ) - ) - & set( - ( - "parent", - "clipId", - "clip", - ) - ) - ) + unset_fields = transport.get_input._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) -def test_create_clip_rest_flattened(): +def test_get_input_rest_flattened(): client = LivestreamServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -14612,43 +14712,40 @@ def test_create_clip_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 = resources.Input() # get arguments that satisfy an http rule for this method - sample_request = { - "parent": "projects/sample1/locations/sample2/channels/sample3" - } + sample_request = {"name": "projects/sample1/locations/sample2/inputs/sample3"} # get truthy value for each flattened field mock_args = dict( - parent="parent_value", - clip=resources.Clip(name="name_value"), - clip_id="clip_id_value", + name="name_value", ) mock_args.update(sample_request) # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 + # Convert return value to protobuf type + return_value = resources.Input.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = 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_clip(**mock_args) + client.get_input(**mock_args) # Establish that the underlying call was 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/*/channels/*}/clips" - % client.transport._host, + "%s/v1/{name=projects/*/locations/*/inputs/*}" % client.transport._host, args[1], ) -def test_create_clip_rest_flattened_error(transport: str = "rest"): +def test_get_input_rest_flattened_error(transport: str = "rest"): client = LivestreamServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -14657,15 +14754,13 @@ def test_create_clip_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_clip( - service.CreateClipRequest(), - parent="parent_value", - clip=resources.Clip(name="name_value"), - clip_id="clip_id_value", + client.get_input( + service.GetInputRequest(), + name="name_value", ) -def test_delete_clip_rest_use_cached_wrapped_rpc(): +def test_delete_input_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -14679,17 +14774,17 @@ def test_delete_clip_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.delete_clip in client._transport._wrapped_methods + assert client._transport.delete_input in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = 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_clip] = mock_rpc + client._transport._wrapped_methods[client._transport.delete_input] = mock_rpc request = {} - client.delete_clip(request) + client.delete_input(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 @@ -14698,14 +14793,14 @@ def test_delete_clip_rest_use_cached_wrapped_rpc(): # subsequent calls should use the cached wrapper wrapper_fn.reset_mock() - client.delete_clip(request) + client.delete_input(request) # Establish 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_clip_rest_required_fields(request_type=service.DeleteClipRequest): +def test_delete_input_rest_required_fields(request_type=service.DeleteInputRequest): transport_class = transports.LivestreamServiceRestTransport request_init = {} @@ -14720,7 +14815,7 @@ def test_delete_clip_rest_required_fields(request_type=service.DeleteClipRequest unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).delete_clip._get_unset_required_fields(jsonified_request) + ).delete_input._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present @@ -14729,7 +14824,7 @@ def test_delete_clip_rest_required_fields(request_type=service.DeleteClipRequest unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).delete_clip._get_unset_required_fields(jsonified_request) + ).delete_input._get_unset_required_fields(jsonified_request) # Check that path parameters and body parameters are not mixing in. assert not set(unset_fields) - set(("request_id",)) jsonified_request.update(unset_fields) @@ -14770,23 +14865,23 @@ def test_delete_clip_rest_required_fields(request_type=service.DeleteClipRequest req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.delete_clip(request) + response = client.delete_input(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_delete_clip_rest_unset_required_fields(): +def test_delete_input_rest_unset_required_fields(): transport = transports.LivestreamServiceRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.delete_clip._get_unset_required_fields({}) + unset_fields = transport.delete_input._get_unset_required_fields({}) assert set(unset_fields) == (set(("requestId",)) & set(("name",))) -def test_delete_clip_rest_flattened(): +def test_delete_input_rest_flattened(): client = LivestreamServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -14798,9 +14893,7 @@ def test_delete_clip_rest_flattened(): return_value = operations_pb2.Operation(name="operations/spam") # get arguments that satisfy an http rule for this method - sample_request = { - "name": "projects/sample1/locations/sample2/channels/sample3/clips/sample4" - } + sample_request = {"name": "projects/sample1/locations/sample2/inputs/sample3"} # get truthy value for each flattened field mock_args = dict( @@ -14816,20 +14909,19 @@ def test_delete_clip_rest_flattened(): req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.delete_clip(**mock_args) + client.delete_input(**mock_args) # Establish that the underlying call was 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/*/channels/*/clips/*}" - % client.transport._host, + "%s/v1/{name=projects/*/locations/*/inputs/*}" % client.transport._host, args[1], ) -def test_delete_clip_rest_flattened_error(transport: str = "rest"): +def test_delete_input_rest_flattened_error(transport: str = "rest"): client = LivestreamServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -14838,13 +14930,13 @@ def test_delete_clip_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_clip( - service.DeleteClipRequest(), + client.delete_input( + service.DeleteInputRequest(), name="name_value", ) -def test_create_asset_rest_use_cached_wrapped_rpc(): +def test_update_input_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -14858,17 +14950,17 @@ def test_create_asset_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.create_asset in client._transport._wrapped_methods + assert client._transport.update_input in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = 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_asset] = mock_rpc + client._transport._wrapped_methods[client._transport.update_input] = mock_rpc request = {} - client.create_asset(request) + client.update_input(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 @@ -14877,19 +14969,17 @@ def test_create_asset_rest_use_cached_wrapped_rpc(): # subsequent calls should use the cached wrapper wrapper_fn.reset_mock() - client.create_asset(request) + client.update_input(request) # Establish 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_asset_rest_required_fields(request_type=service.CreateAssetRequest): +def test_update_input_rest_required_fields(request_type=service.UpdateInputRequest): transport_class = transports.LivestreamServiceRestTransport request_init = {} - request_init["parent"] = "" - request_init["asset_id"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -14897,37 +14987,27 @@ def test_create_asset_rest_required_fields(request_type=service.CreateAssetReque ) # verify fields with default values are dropped - assert "assetId" not in jsonified_request unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).create_asset._get_unset_required_fields(jsonified_request) + ).update_input._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present - assert "assetId" in jsonified_request - assert jsonified_request["assetId"] == request_init["asset_id"] - - jsonified_request["parent"] = "parent_value" - jsonified_request["assetId"] = "asset_id_value" unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).create_asset._get_unset_required_fields(jsonified_request) + ).update_input._get_unset_required_fields(jsonified_request) # Check that path parameters and body parameters are not mixing in. assert not set(unset_fields) - set( ( - "asset_id", "request_id", + "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" - assert "assetId" in jsonified_request - assert jsonified_request["assetId"] == "asset_id_value" client = LivestreamServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -14948,7 +15028,7 @@ def test_create_asset_rest_required_fields(request_type=service.CreateAssetReque 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 @@ -14962,43 +15042,31 @@ def test_create_asset_rest_required_fields(request_type=service.CreateAssetReque req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.create_asset(request) + response = client.update_input(request) - expected_params = [ - ( - "assetId", - "", - ), - ("$alt", "json;enum-encoding=int"), - ] + expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_create_asset_rest_unset_required_fields(): +def test_update_input_rest_unset_required_fields(): transport = transports.LivestreamServiceRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.create_asset._get_unset_required_fields({}) + unset_fields = transport.update_input._get_unset_required_fields({}) assert set(unset_fields) == ( set( ( - "assetId", "requestId", + "updateMask", ) ) - & set( - ( - "parent", - "asset", - "assetId", - ) - ) + & set(("input",)) ) -def test_create_asset_rest_flattened(): +def test_update_input_rest_flattened(): client = LivestreamServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -15010,13 +15078,14 @@ def test_create_asset_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 = { + "input": {"name": "projects/sample1/locations/sample2/inputs/sample3"} + } # get truthy value for each flattened field mock_args = dict( - parent="parent_value", - asset=resources.Asset(name="name_value"), - asset_id="asset_id_value", + input=resources.Input(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) mock_args.update(sample_request) @@ -15028,19 +15097,20 @@ def test_create_asset_rest_flattened(): req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.create_asset(**mock_args) + client.update_input(**mock_args) # Establish that the underlying call was 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/*}/assets" % client.transport._host, + "%s/v1/{input.name=projects/*/locations/*/inputs/*}" + % client.transport._host, args[1], ) -def test_create_asset_rest_flattened_error(transport: str = "rest"): +def test_update_input_rest_flattened_error(transport: str = "rest"): client = LivestreamServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -15049,15 +15119,14 @@ def test_create_asset_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_asset( - service.CreateAssetRequest(), - parent="parent_value", - asset=resources.Asset(name="name_value"), - asset_id="asset_id_value", + client.update_input( + service.UpdateInputRequest(), + input=resources.Input(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) -def test_delete_asset_rest_use_cached_wrapped_rpc(): +def test_create_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: @@ -15071,37 +15140,34 @@ def test_delete_asset_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.delete_asset in client._transport._wrapped_methods + assert client._transport.create_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_asset] = mock_rpc + client._transport._wrapped_methods[client._transport.create_event] = mock_rpc request = {} - client.delete_asset(request) + client.create_event(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_asset(request) + client.create_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_delete_asset_rest_required_fields(request_type=service.DeleteAssetRequest): +def test_create_event_rest_required_fields(request_type=service.CreateEventRequest): transport_class = transports.LivestreamServiceRestTransport request_init = {} - request_init["name"] = "" + request_init["parent"] = "" + request_init["event_id"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -15109,26 +15175,37 @@ def test_delete_asset_rest_required_fields(request_type=service.DeleteAssetReque ) # verify fields with default values are dropped + assert "eventId" not in jsonified_request unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).delete_asset._get_unset_required_fields(jsonified_request) + ).create_event._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present + assert "eventId" in jsonified_request + assert jsonified_request["eventId"] == request_init["event_id"] - jsonified_request["name"] = "name_value" + jsonified_request["parent"] = "parent_value" + jsonified_request["eventId"] = "event_id_value" unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).delete_asset._get_unset_required_fields(jsonified_request) + ).create_event._get_unset_required_fields(jsonified_request) # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("request_id",)) + assert not set(unset_fields) - set( + ( + "event_id", + "request_id", + ) + ) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == "name_value" + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + assert "eventId" in jsonified_request + assert jsonified_request["eventId"] == "event_id_value" client = LivestreamServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -15137,7 +15214,7 @@ def test_delete_asset_rest_required_fields(request_type=service.DeleteAssetReque request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name="operations/spam") + return_value = resources.Event() # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values @@ -15149,36 +15226,60 @@ def test_delete_asset_rest_required_fields(request_type=service.DeleteAssetReque pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "delete", + "method": "post", "query_params": pb_request, } + transcode_result["body"] = pb_request transcode.return_value = transcode_result response_value = Response() response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = resources.Event.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_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_asset(request) + response = client.create_event(request) - expected_params = [("$alt", "json;enum-encoding=int")] + expected_params = [ + ( + "eventId", + "", + ), + ("$alt", "json;enum-encoding=int"), + ] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_delete_asset_rest_unset_required_fields(): +def test_create_event_rest_unset_required_fields(): transport = transports.LivestreamServiceRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.delete_asset._get_unset_required_fields({}) - assert set(unset_fields) == (set(("requestId",)) & set(("name",))) + unset_fields = transport.create_event._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "eventId", + "requestId", + ) + ) + & set( + ( + "parent", + "event", + "eventId", + ) + ) + ) -def test_delete_asset_rest_flattened(): +def test_create_event_rest_flattened(): client = LivestreamServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -15187,38 +15288,45 @@ def test_delete_asset_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 = resources.Event() # get arguments that satisfy an http rule for this method - sample_request = {"name": "projects/sample1/locations/sample2/assets/sample3"} + sample_request = { + "parent": "projects/sample1/locations/sample2/channels/sample3" + } # get truthy value for each flattened field mock_args = dict( - name="name_value", + parent="parent_value", + event=resources.Event(name="name_value"), + event_id="event_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 = resources.Event.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = 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_asset(**mock_args) + client.create_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=projects/*/locations/*/assets/*}" % client.transport._host, + "%s/v1/{parent=projects/*/locations/*/channels/*}/events" + % client.transport._host, args[1], ) -def test_delete_asset_rest_flattened_error(transport: str = "rest"): +def test_create_event_rest_flattened_error(transport: str = "rest"): client = LivestreamServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -15227,13 +15335,15 @@ def test_delete_asset_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_asset( - service.DeleteAssetRequest(), - name="name_value", + client.create_event( + service.CreateEventRequest(), + parent="parent_value", + event=resources.Event(name="name_value"), + event_id="event_id_value", ) -def test_get_asset_rest_use_cached_wrapped_rpc(): +def test_list_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: @@ -15247,33 +15357,33 @@ def test_get_asset_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.get_asset in client._transport._wrapped_methods + assert client._transport.list_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.get_asset] = mock_rpc + client._transport._wrapped_methods[client._transport.list_events] = mock_rpc request = {} - client.get_asset(request) + client.list_events(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.get_asset(request) + client.list_events(request) # Establish 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_asset_rest_required_fields(request_type=service.GetAssetRequest): +def test_list_events_rest_required_fields(request_type=service.ListEventsRequest): transport_class = transports.LivestreamServiceRestTransport request_init = {} - request_init["name"] = "" + request_init["parent"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -15284,21 +15394,30 @@ def test_get_asset_rest_required_fields(request_type=service.GetAssetRequest): unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).get_asset._get_unset_required_fields(jsonified_request) + ).list_events._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_asset._get_unset_required_fields(jsonified_request) + ).list_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", + "order_by", + "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 = LivestreamServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -15307,7 +15426,7 @@ def test_get_asset_rest_required_fields(request_type=service.GetAssetRequest): request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = resources.Asset() + return_value = service.ListEventsResponse() # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values @@ -15328,30 +15447,40 @@ def test_get_asset_rest_required_fields(request_type=service.GetAssetRequest): response_value.status_code = 200 # Convert return value to protobuf type - return_value = resources.Asset.pb(return_value) + return_value = service.ListEventsResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_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_asset(request) + response = client.list_events(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_get_asset_rest_unset_required_fields(): +def test_list_events_rest_unset_required_fields(): transport = transports.LivestreamServiceRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.get_asset._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name",))) + unset_fields = transport.list_events._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "filter", + "orderBy", + "pageSize", + "pageToken", + ) + ) + & set(("parent",)) + ) -def test_get_asset_rest_flattened(): +def test_list_events_rest_flattened(): client = LivestreamServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -15360,14 +15489,16 @@ def test_get_asset_rest_flattened(): # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = resources.Asset() + return_value = service.ListEventsResponse() # get arguments that satisfy an http rule for this method - sample_request = {"name": "projects/sample1/locations/sample2/assets/sample3"} + sample_request = { + "parent": "projects/sample1/locations/sample2/channels/sample3" + } # get truthy value for each flattened field mock_args = dict( - name="name_value", + parent="parent_value", ) mock_args.update(sample_request) @@ -15375,25 +15506,26 @@ def test_get_asset_rest_flattened(): response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = resources.Asset.pb(return_value) + return_value = service.ListEventsResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = 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_asset(**mock_args) + client.list_events(**mock_args) # Establish that the underlying call was 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/*/assets/*}" % client.transport._host, + "%s/v1/{parent=projects/*/locations/*/channels/*}/events" + % client.transport._host, args[1], ) -def test_get_asset_rest_flattened_error(transport: str = "rest"): +def test_list_events_rest_flattened_error(transport: str = "rest"): client = LivestreamServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -15402,53 +15534,116 @@ def test_get_asset_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_asset( - service.GetAssetRequest(), - name="name_value", + client.list_events( + service.ListEventsRequest(), + parent="parent_value", ) -def test_list_assets_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = LivestreamServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() +def test_list_events_rest_pager(transport: str = "rest"): + client = LivestreamServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) - # Ensure method has been cached - assert client._transport.list_assets in client._transport._wrapped_methods + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # TODO(kbandes): remove this mock unless there's a good reason for it. + # with mock.patch.object(path_template, 'transcode') as transcode: + # Set the response as a series of pages + response = ( + service.ListEventsResponse( + events=[ + resources.Event(), + resources.Event(), + resources.Event(), + ], + next_page_token="abc", + ), + service.ListEventsResponse( + events=[], + next_page_token="def", + ), + service.ListEventsResponse( + events=[ + resources.Event(), + ], + next_page_token="ghi", + ), + service.ListEventsResponse( + events=[ + resources.Event(), + resources.Event(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(service.ListEventsResponse.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/channels/sample3" + } + + pager = client.list_events(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, resources.Event) for i in results) + + pages = list(client.list_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_event_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = LivestreamServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should 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_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.list_assets] = mock_rpc + client._transport._wrapped_methods[client._transport.get_event] = mock_rpc request = {} - client.list_assets(request) + client.get_event(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.list_assets(request) + client.get_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_list_assets_rest_required_fields(request_type=service.ListAssetsRequest): +def test_get_event_rest_required_fields(request_type=service.GetEventRequest): transport_class = transports.LivestreamServiceRestTransport request_init = {} - request_init["parent"] = "" + request_init["name"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -15459,30 +15654,21 @@ def test_list_assets_rest_required_fields(request_type=service.ListAssetsRequest unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).list_assets._get_unset_required_fields(jsonified_request) + ).get_event._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_assets._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set( - ( - "filter", - "order_by", - "page_size", - "page_token", - ) - ) + ).get_event._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 = LivestreamServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -15491,7 +15677,7 @@ def test_list_assets_rest_required_fields(request_type=service.ListAssetsRequest request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = service.ListAssetsResponse() + return_value = resources.Event() # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values @@ -15512,40 +15698,30 @@ def test_list_assets_rest_required_fields(request_type=service.ListAssetsRequest response_value.status_code = 200 # Convert return value to protobuf type - return_value = service.ListAssetsResponse.pb(return_value) + return_value = resources.Event.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_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_assets(request) + response = client.get_event(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_list_assets_rest_unset_required_fields(): +def test_get_event_rest_unset_required_fields(): transport = transports.LivestreamServiceRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.list_assets._get_unset_required_fields({}) - assert set(unset_fields) == ( - set( - ( - "filter", - "orderBy", - "pageSize", - "pageToken", - ) - ) - & set(("parent",)) - ) + unset_fields = transport.get_event._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) -def test_list_assets_rest_flattened(): +def test_get_event_rest_flattened(): client = LivestreamServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -15554,14 +15730,16 @@ def test_list_assets_rest_flattened(): # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = service.ListAssetsResponse() + return_value = resources.Event() # get arguments that satisfy an http rule for this method - sample_request = {"parent": "projects/sample1/locations/sample2"} + sample_request = { + "name": "projects/sample1/locations/sample2/channels/sample3/events/sample4" + } # get truthy value for each flattened field mock_args = dict( - parent="parent_value", + name="name_value", ) mock_args.update(sample_request) @@ -15569,25 +15747,26 @@ def test_list_assets_rest_flattened(): response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = service.ListAssetsResponse.pb(return_value) + return_value = resources.Event.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = 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_assets(**mock_args) + client.get_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/{parent=projects/*/locations/*}/assets" % client.transport._host, + "%s/v1/{name=projects/*/locations/*/channels/*/events/*}" + % client.transport._host, args[1], ) -def test_list_assets_rest_flattened_error(transport: str = "rest"): +def test_get_event_rest_flattened_error(transport: str = "rest"): client = LivestreamServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -15596,74 +15775,13 @@ def test_list_assets_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_assets( - service.ListAssetsRequest(), - parent="parent_value", - ) - - -def test_list_assets_rest_pager(transport: str = "rest"): - client = LivestreamServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, "request") as req: - # TODO(kbandes): remove this mock unless there's a good reason for it. - # with mock.patch.object(path_template, 'transcode') as transcode: - # Set the response as a series of pages - response = ( - service.ListAssetsResponse( - assets=[ - resources.Asset(), - resources.Asset(), - resources.Asset(), - ], - next_page_token="abc", - ), - service.ListAssetsResponse( - assets=[], - next_page_token="def", - ), - service.ListAssetsResponse( - assets=[ - resources.Asset(), - ], - next_page_token="ghi", - ), - service.ListAssetsResponse( - assets=[ - resources.Asset(), - resources.Asset(), - ], - ), + client.get_event( + service.GetEventRequest(), + name="name_value", ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(service.ListAssetsResponse.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_assets(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, resources.Asset) for i in results) - - pages = list(client.list_assets(request=sample_request).pages) - for page_, token in zip(pages, ["abc", "def", "ghi", ""]): - assert page_.raw_page.next_page_token == token -def test_get_pool_rest_use_cached_wrapped_rpc(): +def test_delete_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: @@ -15677,29 +15795,29 @@ def test_get_pool_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.get_pool in client._transport._wrapped_methods + assert client._transport.delete_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.get_pool] = mock_rpc + client._transport._wrapped_methods[client._transport.delete_event] = mock_rpc request = {} - client.get_pool(request) + client.delete_event(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.get_pool(request) + client.delete_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_get_pool_rest_required_fields(request_type=service.GetPoolRequest): +def test_delete_event_rest_required_fields(request_type=service.DeleteEventRequest): transport_class = transports.LivestreamServiceRestTransport request_init = {} @@ -15714,7 +15832,7 @@ def test_get_pool_rest_required_fields(request_type=service.GetPoolRequest): unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).get_pool._get_unset_required_fields(jsonified_request) + ).delete_event._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present @@ -15723,7 +15841,9 @@ def test_get_pool_rest_required_fields(request_type=service.GetPoolRequest): unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).get_pool._get_unset_required_fields(jsonified_request) + ).delete_event._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("request_id",)) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone @@ -15737,7 +15857,7 @@ def test_get_pool_rest_required_fields(request_type=service.GetPoolRequest): request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = resources.Pool() + 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 @@ -15749,39 +15869,36 @@ def test_get_pool_rest_required_fields(request_type=service.GetPoolRequest): 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 = resources.Pool.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_pool(request) + response = client.delete_event(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_get_pool_rest_unset_required_fields(): +def test_delete_event_rest_unset_required_fields(): transport = transports.LivestreamServiceRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.get_pool._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name",))) + unset_fields = transport.delete_event._get_unset_required_fields({}) + assert set(unset_fields) == (set(("requestId",)) & set(("name",))) -def test_get_pool_rest_flattened(): +def test_delete_event_rest_flattened(): client = LivestreamServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -15790,10 +15907,12 @@ def test_get_pool_rest_flattened(): # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = resources.Pool() + return_value = None # get arguments that satisfy an http rule for this method - sample_request = {"name": "projects/sample1/locations/sample2/pools/sample3"} + sample_request = { + "name": "projects/sample1/locations/sample2/channels/sample3/events/sample4" + } # get truthy value for each flattened field mock_args = dict( @@ -15804,26 +15923,25 @@ def test_get_pool_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 = resources.Pool.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_pool(**mock_args) + client.delete_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=projects/*/locations/*/pools/*}" % client.transport._host, + "%s/v1/{name=projects/*/locations/*/channels/*/events/*}" + % client.transport._host, args[1], ) -def test_get_pool_rest_flattened_error(transport: str = "rest"): +def test_delete_event_rest_flattened_error(transport: str = "rest"): client = LivestreamServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -15832,13 +15950,13 @@ def test_get_pool_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_pool( - service.GetPoolRequest(), + client.delete_event( + service.DeleteEventRequest(), name="name_value", ) -def test_update_pool_rest_use_cached_wrapped_rpc(): +def test_list_clips_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -15852,36 +15970,33 @@ def test_update_pool_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.update_pool in client._transport._wrapped_methods + assert client._transport.list_clips in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = 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_pool] = mock_rpc + client._transport._wrapped_methods[client._transport.list_clips] = mock_rpc request = {} - client.update_pool(request) + client.list_clips(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_pool(request) + client.list_clips(request) # Establish 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_pool_rest_required_fields(request_type=service.UpdatePoolRequest): +def test_list_clips_rest_required_fields(request_type=service.ListClipsRequest): transport_class = transports.LivestreamServiceRestTransport request_init = {} + request_init["parent"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -15892,24 +16007,30 @@ def test_update_pool_rest_required_fields(request_type=service.UpdatePoolRequest unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).update_pool._get_unset_required_fields(jsonified_request) + ).list_clips._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_pool._get_unset_required_fields(jsonified_request) + ).list_clips._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", + "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 = LivestreamServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -15918,7 +16039,7 @@ def test_update_pool_rest_required_fields(request_type=service.UpdatePoolRequest request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name="operations/spam") + return_value = service.ListClipsResponse() # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values @@ -15930,45 +16051,49 @@ def test_update_pool_rest_required_fields(request_type=service.UpdatePoolRequest 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 = service.ListClipsResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_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_pool(request) + response = client.list_clips(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_update_pool_rest_unset_required_fields(): +def test_list_clips_rest_unset_required_fields(): transport = transports.LivestreamServiceRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.update_pool._get_unset_required_fields({}) + unset_fields = transport.list_clips._get_unset_required_fields({}) assert set(unset_fields) == ( set( ( - "requestId", - "updateMask", + "filter", + "orderBy", + "pageSize", + "pageToken", ) ) - & set(("pool",)) + & set(("parent",)) ) -def test_update_pool_rest_flattened(): +def test_list_clips_rest_flattened(): client = LivestreamServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -15977,41 +16102,43 @@ def test_update_pool_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 = service.ListClipsResponse() # get arguments that satisfy an http rule for this method sample_request = { - "pool": {"name": "projects/sample1/locations/sample2/pools/sample3"} + "parent": "projects/sample1/locations/sample2/channels/sample3" } # get truthy value for each flattened field mock_args = dict( - pool=resources.Pool(name="name_value"), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + parent="parent_value", ) mock_args.update(sample_request) # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 + # Convert return value to protobuf type + return_value = service.ListClipsResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = 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_pool(**mock_args) + client.list_clips(**mock_args) # Establish that the underlying call was made with the expected # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] assert path_template.validate( - "%s/v1/{pool.name=projects/*/locations/*/pools/*}" % client.transport._host, + "%s/v1/{parent=projects/*/locations/*/channels/*}/clips" + % client.transport._host, args[1], ) -def test_update_pool_rest_flattened_error(transport: str = "rest"): +def test_list_clips_rest_flattened_error(transport: str = "rest"): client = LivestreamServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -16020,1382 +16147,5207 @@ def test_update_pool_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_pool( - service.UpdatePoolRequest(), - pool=resources.Pool(name="name_value"), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + client.list_clips( + service.ListClipsRequest(), + parent="parent_value", ) -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.LivestreamServiceGrpcTransport( +def test_list_clips_rest_pager(transport: str = "rest"): + client = LivestreamServiceClient( credentials=ga_credentials.AnonymousCredentials(), + transport=transport, ) - with pytest.raises(ValueError): - client = LivestreamServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - # It is an error to provide a credentials file and a transport instance. - transport = transports.LivestreamServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = LivestreamServiceClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # TODO(kbandes): remove this mock unless there's a good reason for it. + # with mock.patch.object(path_template, 'transcode') as transcode: + # Set the response as a series of pages + response = ( + service.ListClipsResponse( + clips=[ + resources.Clip(), + resources.Clip(), + resources.Clip(), + ], + next_page_token="abc", + ), + service.ListClipsResponse( + clips=[], + next_page_token="def", + ), + service.ListClipsResponse( + clips=[ + resources.Clip(), + ], + next_page_token="ghi", + ), + service.ListClipsResponse( + clips=[ + resources.Clip(), + resources.Clip(), + ], + ), ) + # Two responses for two calls + response = response + response - # It is an error to provide an api_key and a transport instance. - transport = transports.LivestreamServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = LivestreamServiceClient( - client_options=options, - transport=transport, - ) + # Wrap the values into proper Response objs + response = tuple(service.ListClipsResponse.to_json(x) for x in response) + return_values = tuple(Response() for i in response) + for return_val, response_val in zip(return_values, response): + return_val._content = response_val.encode("UTF-8") + return_val.status_code = 200 + req.side_effect = return_values - # It is an error to provide an api_key and a credential. - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = LivestreamServiceClient( - client_options=options, credentials=ga_credentials.AnonymousCredentials() - ) + sample_request = { + "parent": "projects/sample1/locations/sample2/channels/sample3" + } - # It is an error to provide scopes and a transport instance. - transport = transports.LivestreamServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = LivestreamServiceClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) + pager = client.list_clips(request=sample_request) + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, resources.Clip) for i in results) -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.LivestreamServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = LivestreamServiceClient(transport=transport) - assert client.transport is transport + pages = list(client.list_clips(request=sample_request).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.LivestreamServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel +def test_get_clip_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = LivestreamServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) - transport = transports.LivestreamServiceGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel + # Should 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_clip in client._transport._wrapped_methods -@pytest.mark.parametrize( - "transport_class", - [ - transports.LivestreamServiceGrpcTransport, - transports.LivestreamServiceGrpcAsyncIOTransport, - transports.LivestreamServiceRestTransport, - ], -) -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() + # Replace cached wrapped function with mock + mock_rpc = 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_clip] = mock_rpc + request = {} + client.get_clip(request) -def test_transport_kind_grpc(): - transport = LivestreamServiceClient.get_transport_class("grpc")( - credentials=ga_credentials.AnonymousCredentials() - ) - assert transport.kind == "grpc" + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + client.get_clip(request) -def test_initialize_client_w_grpc(): - client = LivestreamServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport="grpc" - ) - assert client is not None + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_create_channel_empty_call_grpc(): - client = LivestreamServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", +def test_get_clip_rest_required_fields(request_type=service.GetClipRequest): + transport_class = transports.LivestreamServiceRestTransport + + 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.create_channel_), "__call__") as call: - call.return_value = operations_pb2.Operation(name="operations/op") - client.create_channel(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 = service.CreateChannelRequest() + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get_clip._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) - assert args[0] == request_msg + # verify required fields with default values are now present + jsonified_request["name"] = "name_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get_clip._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_list_channels_empty_call_grpc(): client = LivestreamServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", + transport="rest", ) + request = request_type(**request_init) - # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.list_channels), "__call__") as call: - call.return_value = service.ListChannelsResponse() - client.list_channels(request=None) + # Designate an appropriate value for the returned response. + return_value = resources.Clip() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_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 = service.ListChannelsRequest() + response_value = Response() + response_value.status_code = 200 - assert args[0] == request_msg + # Convert return value to protobuf type + return_value = resources.Clip.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_get_channel_empty_call_grpc(): - client = LivestreamServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) + response = client.get_clip(request) - # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.get_channel), "__call__") as call: - call.return_value = resources.Channel() - client.get_channel(request=None) + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = service.GetChannelRequest() - assert args[0] == request_msg +def test_get_clip_rest_unset_required_fields(): + transport = transports.LivestreamServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.get_clip._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_channel_empty_call_grpc(): +def test_get_clip_rest_flattened(): client = LivestreamServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", + transport="rest", ) - # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.delete_channel), "__call__") as call: - call.return_value = operations_pb2.Operation(name="operations/op") - client.delete_channel(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = service.DeleteChannelRequest() - - assert args[0] == request_msg + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = resources.Clip() + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/channels/sample3/clips/sample4" + } -# This 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_channel_empty_call_grpc(): - client = LivestreamServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + ) + mock_args.update(sample_request) - # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.update_channel), "__call__") as call: - call.return_value = operations_pb2.Operation(name="operations/op") - client.update_channel(request=None) + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = resources.Clip.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._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 = service.UpdateChannelRequest() + client.get_clip(**mock_args) - assert args[0] == request_msg + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1/{name=projects/*/locations/*/channels/*/clips/*}" + % 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_start_channel_empty_call_grpc(): +def test_get_clip_rest_flattened_error(transport: str = "rest"): client = LivestreamServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", + transport=transport, ) - # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.start_channel), "__call__") as call: - call.return_value = operations_pb2.Operation(name="operations/op") - client.start_channel(request=None) + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_clip( + service.GetClipRequest(), + name="name_value", + ) - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = service.StartChannelRequest() - assert args[0] == request_msg +def test_create_clip_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = LivestreamServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_stop_channel_empty_call_grpc(): - client = LivestreamServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) + # Ensure method has been cached + assert client._transport.create_clip in client._transport._wrapped_methods - # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.stop_channel), "__call__") as call: - call.return_value = operations_pb2.Operation(name="operations/op") - client.stop_channel(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.create_clip] = mock_rpc - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = service.StopChannelRequest() + request = {} + client.create_clip(request) - assert args[0] == request_msg + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_create_input_empty_call_grpc(): - client = LivestreamServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) + client.create_clip(request) - # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.create_input), "__call__") as call: - call.return_value = operations_pb2.Operation(name="operations/op") - client.create_input(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 = service.CreateInputRequest() - assert args[0] == request_msg +def test_create_clip_rest_required_fields(request_type=service.CreateClipRequest): + transport_class = transports.LivestreamServiceRestTransport - -# This 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_inputs_empty_call_grpc(): - client = LivestreamServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", + request_init = {} + request_init["parent"] = "" + request_init["clip_id"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) ) - # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.list_inputs), "__call__") as call: - call.return_value = service.ListInputsResponse() - client.list_inputs(request=None) + # verify fields with default values are dropped + assert "clipId" not in jsonified_request - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = service.ListInputsRequest() + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).create_clip._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) - assert args[0] == request_msg + # verify required fields with default values are now present + assert "clipId" in jsonified_request + assert jsonified_request["clipId"] == request_init["clip_id"] + jsonified_request["parent"] = "parent_value" + jsonified_request["clipId"] = "clip_id_value" -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_get_input_empty_call_grpc(): - client = LivestreamServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).create_clip._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "clip_id", + "request_id", + ) ) + jsonified_request.update(unset_fields) - # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.get_input), "__call__") as call: - call.return_value = resources.Input() - client.get_input(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = service.GetInputRequest() - - assert args[0] == request_msg - + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + assert "clipId" in jsonified_request + assert jsonified_request["clipId"] == "clip_id_value" -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_delete_input_empty_call_grpc(): client = LivestreamServiceClient( 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_input), "__call__") as call: - call.return_value = operations_pb2.Operation(name="operations/op") - client.delete_input(request=None) + # 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 - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = service.DeleteInputRequest() + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) - assert args[0] == request_msg + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.create_clip(request) -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_update_input_empty_call_grpc(): - client = LivestreamServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) + expected_params = [ + ( + "clipId", + "", + ), + ("$alt", "json;enum-encoding=int"), + ] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params - # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.update_input), "__call__") as call: - call.return_value = operations_pb2.Operation(name="operations/op") - client.update_input(request=None) - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = service.UpdateInputRequest() +def test_create_clip_rest_unset_required_fields(): + transport = transports.LivestreamServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) - assert args[0] == request_msg + unset_fields = transport.create_clip._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "clipId", + "requestId", + ) + ) + & set( + ( + "parent", + "clipId", + "clip", + ) + ) + ) -# This 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_event_empty_call_grpc(): +def test_create_clip_rest_flattened(): client = LivestreamServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", + transport="rest", ) - # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.create_event), "__call__") as call: - call.return_value = resources.Event() - client.create_event(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = service.CreateEventRequest() - - assert args[0] == request_msg + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + # get arguments that satisfy an http rule for this method + sample_request = { + "parent": "projects/sample1/locations/sample2/channels/sample3" + } -# This 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_events_empty_call_grpc(): - client = LivestreamServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + clip=resources.Clip(name="name_value"), + clip_id="clip_id_value", + ) + mock_args.update(sample_request) - # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.list_events), "__call__") as call: - call.return_value = service.ListEventsResponse() - client.list_events(request=None) + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = service.ListEventsRequest() + client.create_clip(**mock_args) - assert args[0] == request_msg + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1/{parent=projects/*/locations/*/channels/*}/clips" + % 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_event_empty_call_grpc(): +def test_create_clip_rest_flattened_error(transport: str = "rest"): client = LivestreamServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", + transport=transport, ) - # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.get_event), "__call__") as call: - call.return_value = resources.Event() - client.get_event(request=None) + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.create_clip( + service.CreateClipRequest(), + parent="parent_value", + clip=resources.Clip(name="name_value"), + clip_id="clip_id_value", + ) - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = service.GetEventRequest() - assert args[0] == request_msg +def test_delete_clip_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = LivestreamServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_delete_event_empty_call_grpc(): - client = LivestreamServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.delete_event), "__call__") as call: - call.return_value = None - client.delete_event(request=None) + # Ensure method has been cached + assert client._transport.delete_clip in client._transport._wrapped_methods - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = service.DeleteEventRequest() + # Replace cached wrapped function with mock + mock_rpc = 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_clip] = mock_rpc - assert args[0] == request_msg + request = {} + client.delete_clip(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_list_clips_empty_call_grpc(): - client = LivestreamServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() - # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.list_clips), "__call__") as call: - call.return_value = service.ListClipsResponse() - client.list_clips(request=None) + client.delete_clip(request) - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = service.ListClipsRequest() + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 - assert args[0] == request_msg +def test_delete_clip_rest_required_fields(request_type=service.DeleteClipRequest): + transport_class = transports.LivestreamServiceRestTransport -# This 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_clip_empty_call_grpc(): - client = LivestreamServiceClient( - 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.get_clip), "__call__") as call: - call.return_value = resources.Clip() - client.get_clip(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = service.GetClipRequest() - - assert args[0] == request_msg - + # verify fields with default values are dropped -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_create_clip_empty_call_grpc(): - client = LivestreamServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).delete_clip._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) - # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.create_clip), "__call__") as call: - call.return_value = operations_pb2.Operation(name="operations/op") - client.create_clip(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 = service.CreateClipRequest() + jsonified_request["name"] = "name_value" - assert args[0] == request_msg + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).delete_clip._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("request_id",)) + jsonified_request.update(unset_fields) + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" -# This 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_clip_empty_call_grpc(): client = LivestreamServiceClient( 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_clip), "__call__") as call: - call.return_value = operations_pb2.Operation(name="operations/op") - client.delete_clip(request=None) + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "delete", + "query_params": pb_request, + } + transcode.return_value = transcode_result - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = service.DeleteClipRequest() + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) - assert args[0] == request_msg + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.delete_clip(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_asset_empty_call_grpc(): - client = LivestreamServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params - # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.create_asset), "__call__") as call: - call.return_value = operations_pb2.Operation(name="operations/op") - client.create_asset(request=None) - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = service.CreateAssetRequest() +def test_delete_clip_rest_unset_required_fields(): + transport = transports.LivestreamServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) - assert args[0] == request_msg + unset_fields = transport.delete_clip._get_unset_required_fields({}) + assert set(unset_fields) == (set(("requestId",)) & 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_asset_empty_call_grpc(): +def test_delete_clip_rest_flattened(): client = LivestreamServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", + transport="rest", ) - # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.delete_asset), "__call__") as call: - call.return_value = operations_pb2.Operation(name="operations/op") - client.delete_asset(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = service.DeleteAssetRequest() - - assert args[0] == request_msg + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/channels/sample3/clips/sample4" + } -# This 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_asset_empty_call_grpc(): - client = LivestreamServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + ) + mock_args.update(sample_request) - # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.get_asset), "__call__") as call: - call.return_value = resources.Asset() - client.get_asset(request=None) + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = service.GetAssetRequest() + client.delete_clip(**mock_args) - assert args[0] == request_msg + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1/{name=projects/*/locations/*/channels/*/clips/*}" + % client.transport._host, + args[1], + ) -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_list_assets_empty_call_grpc(): +def test_delete_clip_rest_flattened_error(transport: str = "rest"): client = LivestreamServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", + transport=transport, ) - # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.list_assets), "__call__") as call: - call.return_value = service.ListAssetsResponse() - client.list_assets(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = service.ListAssetsRequest() + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.delete_clip( + service.DeleteClipRequest(), + name="name_value", + ) - assert args[0] == request_msg +def test_create_dvr_session_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = LivestreamServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_get_pool_empty_call_grpc(): - client = LivestreamServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() - # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.get_pool), "__call__") as call: - call.return_value = resources.Pool() - client.get_pool(request=None) + # Ensure method has been cached + assert ( + client._transport.create_dvr_session in client._transport._wrapped_methods + ) - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = service.GetPoolRequest() + # Replace cached wrapped function with mock + mock_rpc = 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_dvr_session + ] = mock_rpc - assert args[0] == request_msg + request = {} + client.create_dvr_session(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_update_pool_empty_call_grpc(): - client = LivestreamServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() - # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.update_pool), "__call__") as call: - call.return_value = operations_pb2.Operation(name="operations/op") - client.update_pool(request=None) + client.create_dvr_session(request) - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = service.UpdatePoolRequest() + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 - assert args[0] == request_msg +def test_create_dvr_session_rest_required_fields( + request_type=service.CreateDvrSessionRequest, +): + transport_class = transports.LivestreamServiceRestTransport -def test_transport_kind_grpc_asyncio(): - transport = LivestreamServiceAsyncClient.get_transport_class("grpc_asyncio")( - credentials=async_anonymous_credentials() + request_init = {} + request_init["parent"] = "" + request_init["dvr_session_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) ) - assert transport.kind == "grpc_asyncio" + # verify fields with default values are dropped + assert "dvrSessionId" not in jsonified_request -def test_initialize_client_w_grpc_asyncio(): - client = LivestreamServiceAsyncClient( - credentials=async_anonymous_credentials(), transport="grpc_asyncio" - ) - assert client is not None + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).create_dvr_session._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + # verify required fields with default values are now present + assert "dvrSessionId" in jsonified_request + assert jsonified_request["dvrSessionId"] == request_init["dvr_session_id"] -# This test is a coverage 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_channel_empty_call_grpc_asyncio(): - client = LivestreamServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) + jsonified_request["parent"] = "parent_value" + jsonified_request["dvrSessionId"] = "dvr_session_id_value" - # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.create_channel_), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).create_dvr_session._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "dvr_session_id", + "request_id", ) - await client.create_channel(request=None) + ) + jsonified_request.update(unset_fields) - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = service.CreateChannelRequest() + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + assert "dvrSessionId" in jsonified_request + assert jsonified_request["dvrSessionId"] == "dvr_session_id_value" - assert args[0] == request_msg + client = LivestreamServiceClient( + 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 -# This test is a coverage 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_channels_empty_call_grpc_asyncio(): - client = LivestreamServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) - # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.list_channels), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - service.ListChannelsResponse( - next_page_token="next_page_token_value", - unreachable=["unreachable_value"], - ) - ) - await client.list_channels(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 = service.ListChannelsRequest() + response = client.create_dvr_session(request) - assert args[0] == request_msg + expected_params = [ + ( + "dvrSessionId", + "", + ), + ("$alt", "json;enum-encoding=int"), + ] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -@pytest.mark.asyncio -async def test_get_channel_empty_call_grpc_asyncio(): - client = LivestreamServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", +def test_create_dvr_session_rest_unset_required_fields(): + transport = transports.LivestreamServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials ) - # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.get_channel), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - resources.Channel( - name="name_value", - active_input="active_input_value", - streaming_state=resources.Channel.StreamingState.STREAMING, + unset_fields = transport.create_dvr_session._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "dvrSessionId", + "requestId", ) ) - await client.get_channel(request=None) + & set( + ( + "parent", + "dvrSessionId", + "dvrSession", + ) + ) + ) - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = service.GetChannelRequest() - assert args[0] == request_msg +def test_create_dvr_session_rest_flattened(): + client = LivestreamServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") -# This test is a coverage 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_channel_empty_call_grpc_asyncio(): - client = LivestreamServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) + # get arguments that satisfy an http rule for this method + sample_request = { + "parent": "projects/sample1/locations/sample2/channels/sample3" + } - # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.delete_channel), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + dvr_session=resources.DvrSession(name="name_value"), + dvr_session_id="dvr_session_id_value", ) - await client.delete_channel(request=None) + mock_args.update(sample_request) - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = service.DeleteChannelRequest() + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - assert args[0] == request_msg + client.create_dvr_session(**mock_args) + # Establish that the underlying call was 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/*/channels/*}/dvrSessions" + % client.transport._host, + args[1], + ) -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -@pytest.mark.asyncio -async def test_update_channel_empty_call_grpc_asyncio(): - client = LivestreamServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", + +def test_create_dvr_session_rest_flattened_error(transport: str = "rest"): + client = LivestreamServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, ) - # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.update_channel), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.create_dvr_session( + service.CreateDvrSessionRequest(), + parent="parent_value", + dvr_session=resources.DvrSession(name="name_value"), + dvr_session_id="dvr_session_id_value", ) - await client.update_channel(request=None) - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = service.UpdateChannelRequest() - assert args[0] == request_msg +def test_list_dvr_sessions_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = LivestreamServiceClient( + 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_start_channel_empty_call_grpc_asyncio(): - client = LivestreamServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) + # Ensure method has been cached + assert client._transport.list_dvr_sessions in client._transport._wrapped_methods - # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.start_channel), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. ) - await client.start_channel(request=None) + client._transport._wrapped_methods[ + client._transport.list_dvr_sessions + ] = mock_rpc - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = service.StartChannelRequest() + request = {} + client.list_dvr_sessions(request) - assert args[0] == request_msg + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + client.list_dvr_sessions(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_stop_channel_empty_call_grpc_asyncio(): - client = LivestreamServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_list_dvr_sessions_rest_required_fields( + request_type=service.ListDvrSessionsRequest, +): + transport_class = transports.LivestreamServiceRestTransport + + 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.stop_channel), "__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.stop_channel(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 = service.StopChannelRequest() + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).list_dvr_sessions._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) - assert args[0] == request_msg + # verify required fields with default values are now present + jsonified_request["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_create_input_empty_call_grpc_asyncio(): - client = LivestreamServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).list_dvr_sessions._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) - # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.create_input), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") - ) - await client.create_input(request=None) + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = service.CreateInputRequest() + client = LivestreamServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) - assert args[0] == request_msg + # Designate an appropriate value for the returned response. + return_value = service.ListDvrSessionsResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_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_list_inputs_empty_call_grpc_asyncio(): - client = LivestreamServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) + # Convert return value to protobuf type + return_value = service.ListDvrSessionsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) - # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.list_inputs), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - service.ListInputsResponse( - next_page_token="next_page_token_value", - unreachable=["unreachable_value"], - ) - ) - await client.list_inputs(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 = service.ListInputsRequest() + response = client.list_dvr_sessions(request) - assert args[0] == request_msg + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -@pytest.mark.asyncio -async def test_get_input_empty_call_grpc_asyncio(): - client = LivestreamServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", +def test_list_dvr_sessions_rest_unset_required_fields(): + transport = transports.LivestreamServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials ) - # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.get_input), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - resources.Input( - name="name_value", - type_=resources.Input.Type.RTMP_PUSH, - tier=resources.Input.Tier.SD, - uri="uri_value", + unset_fields = transport.list_dvr_sessions._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "filter", + "orderBy", + "pageSize", + "pageToken", ) ) - await client.get_input(request=None) + & set(("parent",)) + ) - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = service.GetInputRequest() - assert args[0] == request_msg +def test_list_dvr_sessions_rest_flattened(): + client = LivestreamServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = service.ListDvrSessionsResponse() -# This test is a coverage 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_input_empty_call_grpc_asyncio(): - client = LivestreamServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) + # get arguments that satisfy an http rule for this method + sample_request = { + "parent": "projects/sample1/locations/sample2/channels/sample3" + } - # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.delete_input), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", ) - await client.delete_input(request=None) + mock_args.update(sample_request) - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = service.DeleteInputRequest() + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = service.ListDvrSessionsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - assert args[0] == request_msg + client.list_dvr_sessions(**mock_args) + + # Establish that the underlying call was 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/*/channels/*}/dvrSessions" + % client.transport._host, + args[1], + ) -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -@pytest.mark.asyncio -async def test_update_input_empty_call_grpc_asyncio(): - client = LivestreamServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", +def test_list_dvr_sessions_rest_flattened_error(transport: str = "rest"): + client = LivestreamServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, ) - # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.update_input), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_dvr_sessions( + service.ListDvrSessionsRequest(), + parent="parent_value", ) - await client.update_input(request=None) - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = service.UpdateInputRequest() - assert args[0] == request_msg +def test_list_dvr_sessions_rest_pager(transport: str = "rest"): + client = LivestreamServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # TODO(kbandes): remove this mock unless there's a good reason for it. + # with mock.patch.object(path_template, 'transcode') as transcode: + # Set the response as a series of pages + response = ( + service.ListDvrSessionsResponse( + dvr_sessions=[ + resources.DvrSession(), + resources.DvrSession(), + resources.DvrSession(), + ], + next_page_token="abc", + ), + service.ListDvrSessionsResponse( + dvr_sessions=[], + next_page_token="def", + ), + service.ListDvrSessionsResponse( + dvr_sessions=[ + resources.DvrSession(), + ], + next_page_token="ghi", + ), + service.ListDvrSessionsResponse( + dvr_sessions=[ + resources.DvrSession(), + resources.DvrSession(), + ], + ), + ) + # Two responses for two calls + response = response + response + # Wrap the values into proper Response objs + response = tuple(service.ListDvrSessionsResponse.to_json(x) for x in response) + return_values = tuple(Response() for i in response) + for return_val, response_val in zip(return_values, response): + return_val._content = response_val.encode("UTF-8") + return_val.status_code = 200 + req.side_effect = return_values -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -@pytest.mark.asyncio -async def test_create_event_empty_call_grpc_asyncio(): - client = LivestreamServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) + sample_request = { + "parent": "projects/sample1/locations/sample2/channels/sample3" + } - # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.create_event), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - resources.Event( - name="name_value", - execute_now=True, - state=resources.Event.State.SCHEDULED, - ) + pager = client.list_dvr_sessions(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, resources.DvrSession) for i in results) + + pages = list(client.list_dvr_sessions(request=sample_request).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +def test_get_dvr_session_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = LivestreamServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - await client.create_event(request=None) - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = service.CreateEventRequest() + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() - assert args[0] == request_msg + # Ensure method has been cached + assert client._transport.get_dvr_session in client._transport._wrapped_methods + # Replace cached wrapped function with mock + mock_rpc = 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_dvr_session] = 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. -@pytest.mark.asyncio -async def test_list_events_empty_call_grpc_asyncio(): - client = LivestreamServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", + request = {} + client.get_dvr_session(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_dvr_session(request) + + # Establish 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_dvr_session_rest_required_fields( + request_type=service.GetDvrSessionRequest, +): + transport_class = transports.LivestreamServiceRestTransport + + 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_events), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - service.ListEventsResponse( - next_page_token="next_page_token_value", - unreachable=["unreachable_value"], - ) - ) - await client.list_events(request=None) + # verify fields with default values are dropped - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = service.ListEventsRequest() + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get_dvr_session._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) - assert args[0] == request_msg + # verify required fields with default values are now present + jsonified_request["name"] = "name_value" -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -@pytest.mark.asyncio -async def test_get_event_empty_call_grpc_asyncio(): - client = LivestreamServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get_dvr_session._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 = LivestreamServiceClient( + 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_event), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - resources.Event( - name="name_value", - execute_now=True, - state=resources.Event.State.SCHEDULED, - ) + # Designate an appropriate value for the returned response. + return_value = resources.DvrSession() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_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 = resources.DvrSession.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_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_dvr_session(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_get_dvr_session_rest_unset_required_fields(): + transport = transports.LivestreamServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.get_dvr_session._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) + + +def test_get_dvr_session_rest_flattened(): + client = LivestreamServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = resources.DvrSession() + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/channels/sample3/dvrSessions/sample4" + } + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", ) - await client.get_event(request=None) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = resources.DvrSession.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = 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_dvr_session(**mock_args) + + # Establish that the underlying call was 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/*/channels/*/dvrSessions/*}" + % client.transport._host, + args[1], + ) + + +def test_get_dvr_session_rest_flattened_error(transport: str = "rest"): + client = LivestreamServiceClient( + credentials=ga_credentials.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_dvr_session( + service.GetDvrSessionRequest(), + name="name_value", + ) + + +def test_delete_dvr_session_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = LivestreamServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should 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_dvr_session in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = 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_dvr_session + ] = mock_rpc + + request = {} + client.delete_dvr_session(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_dvr_session(request) + + # Establish 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_dvr_session_rest_required_fields( + request_type=service.DeleteDvrSessionRequest, +): + transport_class = transports.LivestreamServiceRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).delete_dvr_session._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_dvr_session._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("request_id",)) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + + client = LivestreamServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "delete", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.delete_dvr_session(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_delete_dvr_session_rest_unset_required_fields(): + transport = transports.LivestreamServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.delete_dvr_session._get_unset_required_fields({}) + assert set(unset_fields) == (set(("requestId",)) & set(("name",))) + + +def test_delete_dvr_session_rest_flattened(): + client = LivestreamServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/channels/sample3/dvrSessions/sample4" + } + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.delete_dvr_session(**mock_args) + + # Establish that the underlying call was 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/*/channels/*/dvrSessions/*}" + % client.transport._host, + args[1], + ) + + +def test_delete_dvr_session_rest_flattened_error(transport: str = "rest"): + client = LivestreamServiceClient( + credentials=ga_credentials.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_dvr_session( + service.DeleteDvrSessionRequest(), + name="name_value", + ) + + +def test_update_dvr_session_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = LivestreamServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should 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_dvr_session in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = 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_dvr_session + ] = mock_rpc + + request = {} + client.update_dvr_session(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_dvr_session(request) + + # Establish 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_dvr_session_rest_required_fields( + request_type=service.UpdateDvrSessionRequest, +): + transport_class = transports.LivestreamServiceRestTransport + + 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_dvr_session._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_dvr_session._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "request_id", + "update_mask", + ) + ) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + + client = LivestreamServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "patch", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.update_dvr_session(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_update_dvr_session_rest_unset_required_fields(): + transport = transports.LivestreamServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.update_dvr_session._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "requestId", + "updateMask", + ) + ) + & set( + ( + "updateMask", + "dvrSession", + ) + ) + ) + + +def test_update_dvr_session_rest_flattened(): + client = LivestreamServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # get arguments that satisfy an http rule for this method + sample_request = { + "dvr_session": { + "name": "projects/sample1/locations/sample2/channels/sample3/dvrSessions/sample4" + } + } + + # get truthy value for each flattened field + mock_args = dict( + dvr_session=resources.DvrSession(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.update_dvr_session(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1/{dvr_session.name=projects/*/locations/*/channels/*/dvrSessions/*}" + % client.transport._host, + args[1], + ) + + +def test_update_dvr_session_rest_flattened_error(transport: str = "rest"): + client = LivestreamServiceClient( + credentials=ga_credentials.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_dvr_session( + service.UpdateDvrSessionRequest(), + dvr_session=resources.DvrSession(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +def test_create_asset_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = LivestreamServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should 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_asset in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_asset] = mock_rpc + + request = {} + client.create_asset(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_asset(request) + + # Establish 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_asset_rest_required_fields(request_type=service.CreateAssetRequest): + transport_class = transports.LivestreamServiceRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["asset_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 "assetId" not in jsonified_request + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).create_asset._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + assert "assetId" in jsonified_request + assert jsonified_request["assetId"] == request_init["asset_id"] + + jsonified_request["parent"] = "parent_value" + jsonified_request["assetId"] = "asset_id_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).create_asset._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "asset_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 "assetId" in jsonified_request + assert jsonified_request["assetId"] == "asset_id_value" + + client = LivestreamServiceClient( + 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_asset(request) + + expected_params = [ + ( + "assetId", + "", + ), + ("$alt", "json;enum-encoding=int"), + ] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_create_asset_rest_unset_required_fields(): + transport = transports.LivestreamServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.create_asset._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "assetId", + "requestId", + ) + ) + & set( + ( + "parent", + "asset", + "assetId", + ) + ) + ) + + +def test_create_asset_rest_flattened(): + client = LivestreamServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # get arguments that satisfy an http rule for this method + sample_request = {"parent": "projects/sample1/locations/sample2"} + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + asset=resources.Asset(name="name_value"), + asset_id="asset_id_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.create_asset(**mock_args) + + # Establish that the underlying call was 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/*}/assets" % client.transport._host, + args[1], + ) + + +def test_create_asset_rest_flattened_error(transport: str = "rest"): + client = LivestreamServiceClient( + credentials=ga_credentials.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_asset( + service.CreateAssetRequest(), + parent="parent_value", + asset=resources.Asset(name="name_value"), + asset_id="asset_id_value", + ) + + +def test_delete_asset_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = LivestreamServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should 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_asset in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_asset] = mock_rpc + + request = {} + client.delete_asset(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_asset(request) + + # Establish 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_asset_rest_required_fields(request_type=service.DeleteAssetRequest): + transport_class = transports.LivestreamServiceRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).delete_asset._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_asset._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("request_id",)) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + + client = LivestreamServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "delete", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.delete_asset(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_delete_asset_rest_unset_required_fields(): + transport = transports.LivestreamServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.delete_asset._get_unset_required_fields({}) + assert set(unset_fields) == (set(("requestId",)) & set(("name",))) + + +def test_delete_asset_rest_flattened(): + client = LivestreamServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # get arguments that satisfy an http rule for this method + sample_request = {"name": "projects/sample1/locations/sample2/assets/sample3"} + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.delete_asset(**mock_args) + + # Establish that the underlying call was 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/*/assets/*}" % client.transport._host, + args[1], + ) + + +def test_delete_asset_rest_flattened_error(transport: str = "rest"): + client = LivestreamServiceClient( + credentials=ga_credentials.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_asset( + service.DeleteAssetRequest(), + name="name_value", + ) + + +def test_get_asset_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = LivestreamServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should 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_asset in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_asset] = mock_rpc + + request = {} + client.get_asset(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_asset(request) + + # Establish 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_asset_rest_required_fields(request_type=service.GetAssetRequest): + transport_class = transports.LivestreamServiceRestTransport + + 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_asset._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_asset._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 = LivestreamServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = resources.Asset() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_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 = resources.Asset.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_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_asset(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_get_asset_rest_unset_required_fields(): + transport = transports.LivestreamServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.get_asset._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) + + +def test_get_asset_rest_flattened(): + client = LivestreamServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = resources.Asset() + + # get arguments that satisfy an http rule for this method + sample_request = {"name": "projects/sample1/locations/sample2/assets/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 = resources.Asset.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = 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_asset(**mock_args) + + # Establish that the underlying call was 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/*/assets/*}" % client.transport._host, + args[1], + ) + + +def test_get_asset_rest_flattened_error(transport: str = "rest"): + client = LivestreamServiceClient( + credentials=ga_credentials.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_asset( + service.GetAssetRequest(), + name="name_value", + ) + + +def test_list_assets_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = LivestreamServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should 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_assets in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_assets] = mock_rpc + + request = {} + client.list_assets(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_assets(request) + + # Establish 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_assets_rest_required_fields(request_type=service.ListAssetsRequest): + transport_class = transports.LivestreamServiceRestTransport + + 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_assets._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_assets._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 = LivestreamServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = service.ListAssetsResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "get", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = service.ListAssetsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_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_assets(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_list_assets_rest_unset_required_fields(): + transport = transports.LivestreamServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.list_assets._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "filter", + "orderBy", + "pageSize", + "pageToken", + ) + ) + & set(("parent",)) + ) + + +def test_list_assets_rest_flattened(): + client = LivestreamServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = service.ListAssetsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {"parent": "projects/sample1/locations/sample2"} + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = service.ListAssetsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = 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_assets(**mock_args) + + # Establish that the underlying call was 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/*}/assets" % client.transport._host, + args[1], + ) + + +def test_list_assets_rest_flattened_error(transport: str = "rest"): + client = LivestreamServiceClient( + credentials=ga_credentials.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_assets( + service.ListAssetsRequest(), + parent="parent_value", + ) + + +def test_list_assets_rest_pager(transport: str = "rest"): + client = LivestreamServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # TODO(kbandes): remove this mock unless there's a good reason for it. + # with mock.patch.object(path_template, 'transcode') as transcode: + # Set the response as a series of pages + response = ( + service.ListAssetsResponse( + assets=[ + resources.Asset(), + resources.Asset(), + resources.Asset(), + ], + next_page_token="abc", + ), + service.ListAssetsResponse( + assets=[], + next_page_token="def", + ), + service.ListAssetsResponse( + assets=[ + resources.Asset(), + ], + next_page_token="ghi", + ), + service.ListAssetsResponse( + assets=[ + resources.Asset(), + resources.Asset(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(service.ListAssetsResponse.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_assets(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, resources.Asset) for i in results) + + pages = list(client.list_assets(request=sample_request).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +def test_get_pool_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = LivestreamServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should 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_pool in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_pool] = mock_rpc + + request = {} + client.get_pool(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_pool(request) + + # Establish 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_pool_rest_required_fields(request_type=service.GetPoolRequest): + transport_class = transports.LivestreamServiceRestTransport + + 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_pool._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_pool._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 = LivestreamServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = resources.Pool() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_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 = resources.Pool.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_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_pool(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_get_pool_rest_unset_required_fields(): + transport = transports.LivestreamServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.get_pool._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) + + +def test_get_pool_rest_flattened(): + client = LivestreamServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = resources.Pool() + + # get arguments that satisfy an http rule for this method + sample_request = {"name": "projects/sample1/locations/sample2/pools/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 = resources.Pool.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = 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_pool(**mock_args) + + # Establish that the underlying call was 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/*/pools/*}" % client.transport._host, + args[1], + ) + + +def test_get_pool_rest_flattened_error(transport: str = "rest"): + client = LivestreamServiceClient( + credentials=ga_credentials.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_pool( + service.GetPoolRequest(), + name="name_value", + ) + + +def test_update_pool_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = LivestreamServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should 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_pool in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_pool] = mock_rpc + + request = {} + client.update_pool(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_pool(request) + + # Establish 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_pool_rest_required_fields(request_type=service.UpdatePoolRequest): + transport_class = transports.LivestreamServiceRestTransport + + 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_pool._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_pool._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "request_id", + "update_mask", + ) + ) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + + client = LivestreamServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "patch", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.update_pool(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_update_pool_rest_unset_required_fields(): + transport = transports.LivestreamServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.update_pool._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "requestId", + "updateMask", + ) + ) + & set(("pool",)) + ) + + +def test_update_pool_rest_flattened(): + client = LivestreamServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # get arguments that satisfy an http rule for this method + sample_request = { + "pool": {"name": "projects/sample1/locations/sample2/pools/sample3"} + } + + # get truthy value for each flattened field + mock_args = dict( + pool=resources.Pool(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.update_pool(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1/{pool.name=projects/*/locations/*/pools/*}" % client.transport._host, + args[1], + ) + + +def test_update_pool_rest_flattened_error(transport: str = "rest"): + client = LivestreamServiceClient( + credentials=ga_credentials.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_pool( + service.UpdatePoolRequest(), + pool=resources.Pool(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.LivestreamServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = LivestreamServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.LivestreamServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = LivestreamServiceClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.LivestreamServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = LivestreamServiceClient( + 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 = LivestreamServiceClient( + client_options=options, credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.LivestreamServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = LivestreamServiceClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.LivestreamServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = LivestreamServiceClient(transport=transport) + assert client.transport is transport + + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.LivestreamServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.LivestreamServiceGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.LivestreamServiceGrpcTransport, + transports.LivestreamServiceGrpcAsyncIOTransport, + transports.LivestreamServiceRestTransport, + ], +) +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 = LivestreamServiceClient.get_transport_class("grpc")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "grpc" + + +def test_initialize_client_w_grpc(): + client = LivestreamServiceClient( + 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_channel_empty_call_grpc(): + client = LivestreamServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.create_channel_), "__call__") as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.create_channel(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.CreateChannelRequest() + + assert args[0] == request_msg + + +# This 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_channels_empty_call_grpc(): + client = LivestreamServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.list_channels), "__call__") as call: + call.return_value = service.ListChannelsResponse() + client.list_channels(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.ListChannelsRequest() + + assert args[0] == request_msg + + +# This 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_channel_empty_call_grpc(): + client = LivestreamServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_channel), "__call__") as call: + call.return_value = resources.Channel() + client.get_channel(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.GetChannelRequest() + + assert args[0] == request_msg + + +# This 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_channel_empty_call_grpc(): + client = LivestreamServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.delete_channel), "__call__") as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.delete_channel(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.DeleteChannelRequest() + + assert args[0] == request_msg + + +# This 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_channel_empty_call_grpc(): + client = LivestreamServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.update_channel), "__call__") as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.update_channel(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.UpdateChannelRequest() + + assert args[0] == request_msg + + +# This 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_channel_empty_call_grpc(): + client = LivestreamServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.start_channel), "__call__") as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.start_channel(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.StartChannelRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_stop_channel_empty_call_grpc(): + client = LivestreamServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.stop_channel), "__call__") as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.stop_channel(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.StopChannelRequest() + + assert args[0] == request_msg + + +# This 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_input_empty_call_grpc(): + client = LivestreamServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.create_input), "__call__") as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.create_input(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.CreateInputRequest() + + assert args[0] == request_msg + + +# This 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_inputs_empty_call_grpc(): + client = LivestreamServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.list_inputs), "__call__") as call: + call.return_value = service.ListInputsResponse() + client.list_inputs(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.ListInputsRequest() + + assert args[0] == request_msg + + +# This 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_input_empty_call_grpc(): + client = LivestreamServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_input), "__call__") as call: + call.return_value = resources.Input() + client.get_input(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.GetInputRequest() + + assert args[0] == request_msg + + +# This 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_input_empty_call_grpc(): + client = LivestreamServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.delete_input), "__call__") as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.delete_input(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.DeleteInputRequest() + + assert args[0] == request_msg + + +# This 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_input_empty_call_grpc(): + client = LivestreamServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.update_input), "__call__") as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.update_input(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.UpdateInputRequest() + + assert args[0] == request_msg + + +# This 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_event_empty_call_grpc(): + client = LivestreamServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.create_event), "__call__") as call: + call.return_value = resources.Event() + client.create_event(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.CreateEventRequest() + + assert args[0] == request_msg + + +# This 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_events_empty_call_grpc(): + client = LivestreamServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.list_events), "__call__") as call: + call.return_value = service.ListEventsResponse() + client.list_events(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.ListEventsRequest() + + assert args[0] == request_msg + + +# This 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_event_empty_call_grpc(): + client = LivestreamServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_event), "__call__") as call: + call.return_value = resources.Event() + client.get_event(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.GetEventRequest() + + assert args[0] == request_msg + + +# This 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_event_empty_call_grpc(): + client = LivestreamServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.delete_event), "__call__") as call: + call.return_value = None + client.delete_event(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.DeleteEventRequest() + + assert args[0] == request_msg + + +# This 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_clips_empty_call_grpc(): + client = LivestreamServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.list_clips), "__call__") as call: + call.return_value = service.ListClipsResponse() + client.list_clips(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.ListClipsRequest() + + assert args[0] == request_msg + + +# This 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_clip_empty_call_grpc(): + client = LivestreamServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_clip), "__call__") as call: + call.return_value = resources.Clip() + client.get_clip(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.GetClipRequest() + + assert args[0] == request_msg + + +# This 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_clip_empty_call_grpc(): + client = LivestreamServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.create_clip), "__call__") as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.create_clip(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.CreateClipRequest() + + assert args[0] == request_msg + + +# This 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_clip_empty_call_grpc(): + client = LivestreamServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.delete_clip), "__call__") as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.delete_clip(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.DeleteClipRequest() + + assert args[0] == request_msg + + +# This 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_dvr_session_empty_call_grpc(): + client = LivestreamServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_dvr_session), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.create_dvr_session(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.CreateDvrSessionRequest() + + assert args[0] == request_msg + + +# This 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_dvr_sessions_empty_call_grpc(): + client = LivestreamServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_dvr_sessions), "__call__" + ) as call: + call.return_value = service.ListDvrSessionsResponse() + client.list_dvr_sessions(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.ListDvrSessionsRequest() + + assert args[0] == request_msg + + +# This 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_dvr_session_empty_call_grpc(): + client = LivestreamServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_dvr_session), "__call__") as call: + call.return_value = resources.DvrSession() + client.get_dvr_session(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.GetDvrSessionRequest() + + assert args[0] == request_msg + + +# This 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_dvr_session_empty_call_grpc(): + client = LivestreamServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_dvr_session), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.delete_dvr_session(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.DeleteDvrSessionRequest() + + assert args[0] == request_msg + + +# This 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_dvr_session_empty_call_grpc(): + client = LivestreamServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_dvr_session), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.update_dvr_session(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.UpdateDvrSessionRequest() + + assert args[0] == request_msg + + +# This 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_asset_empty_call_grpc(): + client = LivestreamServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.create_asset), "__call__") as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.create_asset(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.CreateAssetRequest() + + assert args[0] == request_msg + + +# This 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_asset_empty_call_grpc(): + client = LivestreamServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.delete_asset), "__call__") as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.delete_asset(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.DeleteAssetRequest() + + assert args[0] == request_msg + + +# This 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_asset_empty_call_grpc(): + client = LivestreamServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_asset), "__call__") as call: + call.return_value = resources.Asset() + client.get_asset(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.GetAssetRequest() + + assert args[0] == request_msg + + +# This 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_assets_empty_call_grpc(): + client = LivestreamServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.list_assets), "__call__") as call: + call.return_value = service.ListAssetsResponse() + client.list_assets(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.ListAssetsRequest() + + assert args[0] == request_msg + + +# This 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_pool_empty_call_grpc(): + client = LivestreamServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_pool), "__call__") as call: + call.return_value = resources.Pool() + client.get_pool(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.GetPoolRequest() + + assert args[0] == request_msg + + +# This 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_pool_empty_call_grpc(): + client = LivestreamServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.update_pool), "__call__") as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.update_pool(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.UpdatePoolRequest() + + assert args[0] == request_msg + + +def test_transport_kind_grpc_asyncio(): + transport = LivestreamServiceAsyncClient.get_transport_class("grpc_asyncio")( + credentials=async_anonymous_credentials() + ) + assert transport.kind == "grpc_asyncio" + + +def test_initialize_client_w_grpc_asyncio(): + client = LivestreamServiceAsyncClient( + 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_channel_empty_call_grpc_asyncio(): + client = LivestreamServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.create_channel_), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + await client.create_channel(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.CreateChannelRequest() + + assert args[0] == request_msg + + +# This test is a coverage 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_channels_empty_call_grpc_asyncio(): + client = LivestreamServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.list_channels), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + service.ListChannelsResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], + ) + ) + await client.list_channels(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.ListChannelsRequest() + + assert args[0] == request_msg + + +# This test is a coverage 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_channel_empty_call_grpc_asyncio(): + client = LivestreamServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_channel), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + resources.Channel( + name="name_value", + active_input="active_input_value", + streaming_state=resources.Channel.StreamingState.STREAMING, + ) + ) + await client.get_channel(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.GetChannelRequest() + + assert args[0] == request_msg + + +# This test is a coverage 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_channel_empty_call_grpc_asyncio(): + client = LivestreamServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.delete_channel), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + await client.delete_channel(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.DeleteChannelRequest() + + assert args[0] == request_msg + + +# This test is a coverage 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_channel_empty_call_grpc_asyncio(): + client = LivestreamServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.update_channel), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + await client.update_channel(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.UpdateChannelRequest() + + assert args[0] == request_msg + + +# This test is a coverage 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_channel_empty_call_grpc_asyncio(): + client = LivestreamServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.start_channel), "__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_channel(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.StartChannelRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_stop_channel_empty_call_grpc_asyncio(): + client = LivestreamServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.stop_channel), "__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.stop_channel(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.StopChannelRequest() + + assert args[0] == request_msg + + +# This test is a coverage 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_input_empty_call_grpc_asyncio(): + client = LivestreamServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.create_input), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + await client.create_input(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.CreateInputRequest() + + assert args[0] == request_msg + + +# This test is a coverage 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_inputs_empty_call_grpc_asyncio(): + client = LivestreamServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.list_inputs), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + service.ListInputsResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], + ) + ) + await client.list_inputs(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.ListInputsRequest() + + assert args[0] == request_msg + + +# This test is a coverage 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_input_empty_call_grpc_asyncio(): + client = LivestreamServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_input), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + resources.Input( + name="name_value", + type_=resources.Input.Type.RTMP_PUSH, + tier=resources.Input.Tier.SD, + uri="uri_value", + ) + ) + await client.get_input(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.GetInputRequest() + + assert args[0] == request_msg + + +# This test is a coverage 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_input_empty_call_grpc_asyncio(): + client = LivestreamServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.delete_input), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + await client.delete_input(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.DeleteInputRequest() + + assert args[0] == request_msg + + +# This test is a coverage 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_input_empty_call_grpc_asyncio(): + client = LivestreamServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.update_input), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + await client.update_input(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.UpdateInputRequest() + + assert args[0] == request_msg + + +# This test is a coverage 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_event_empty_call_grpc_asyncio(): + client = LivestreamServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.create_event), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + resources.Event( + name="name_value", + execute_now=True, + state=resources.Event.State.SCHEDULED, + ) + ) + await client.create_event(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.CreateEventRequest() + + assert args[0] == request_msg + + +# This test is a coverage 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_events_empty_call_grpc_asyncio(): + client = LivestreamServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.list_events), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + service.ListEventsResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], + ) + ) + await client.list_events(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.ListEventsRequest() + + assert args[0] == request_msg + + +# This test is a coverage 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_event_empty_call_grpc_asyncio(): + client = LivestreamServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_event), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + resources.Event( + name="name_value", + execute_now=True, + state=resources.Event.State.SCHEDULED, + ) + ) + await client.get_event(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.GetEventRequest() + + assert args[0] == request_msg + + +# This test is a coverage 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_event_empty_call_grpc_asyncio(): + client = LivestreamServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.delete_event), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_event(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.DeleteEventRequest() + + assert args[0] == request_msg + + +# This test is a coverage 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_clips_empty_call_grpc_asyncio(): + client = LivestreamServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.list_clips), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + service.ListClipsResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], + ) + ) + await client.list_clips(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.ListClipsRequest() + + assert args[0] == request_msg + + +# This test is a coverage 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_clip_empty_call_grpc_asyncio(): + client = LivestreamServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_clip), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + resources.Clip( + name="name_value", + state=resources.Clip.State.PENDING, + output_uri="output_uri_value", + output_type=resources.Clip.OutputType.MANIFEST, + ) + ) + await client.get_clip(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.GetClipRequest() + + assert args[0] == request_msg + + +# This test is a coverage 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_clip_empty_call_grpc_asyncio(): + client = LivestreamServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.create_clip), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + await client.create_clip(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.CreateClipRequest() + + assert args[0] == request_msg + + +# This test is a coverage 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_clip_empty_call_grpc_asyncio(): + client = LivestreamServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.delete_clip), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + await client.delete_clip(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.DeleteClipRequest() + + assert args[0] == request_msg + + +# This test is a coverage 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_dvr_session_empty_call_grpc_asyncio(): + client = LivestreamServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_dvr_session), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + await client.create_dvr_session(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.CreateDvrSessionRequest() + + assert args[0] == request_msg + + +# This test is a coverage 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_dvr_sessions_empty_call_grpc_asyncio(): + client = LivestreamServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_dvr_sessions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + service.ListDvrSessionsResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], + ) + ) + await client.list_dvr_sessions(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.ListDvrSessionsRequest() + + assert args[0] == request_msg + + +# This test is a coverage 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_dvr_session_empty_call_grpc_asyncio(): + client = LivestreamServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_dvr_session), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + resources.DvrSession( + name="name_value", + state=resources.DvrSession.State.PENDING, + ) + ) + await client.get_dvr_session(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.GetDvrSessionRequest() + + assert args[0] == request_msg + + +# This test is a coverage 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_dvr_session_empty_call_grpc_asyncio(): + client = LivestreamServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_dvr_session), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + await client.delete_dvr_session(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.DeleteDvrSessionRequest() + + assert args[0] == request_msg + + +# This test is a coverage 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_dvr_session_empty_call_grpc_asyncio(): + client = LivestreamServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_dvr_session), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + await client.update_dvr_session(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.UpdateDvrSessionRequest() + + assert args[0] == request_msg + + +# This test is a coverage 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_asset_empty_call_grpc_asyncio(): + client = LivestreamServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.create_asset), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + await client.create_asset(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.CreateAssetRequest() + + assert args[0] == request_msg + + +# This test is a coverage 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_asset_empty_call_grpc_asyncio(): + client = LivestreamServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.delete_asset), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + await client.delete_asset(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.DeleteAssetRequest() + + assert args[0] == request_msg + + +# This test is a coverage 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_asset_empty_call_grpc_asyncio(): + client = LivestreamServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_asset), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + resources.Asset( + name="name_value", + crc32c="crc32c_value", + state=resources.Asset.State.CREATING, + ) + ) + await client.get_asset(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.GetAssetRequest() + + assert args[0] == request_msg + + +# This test is a coverage 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_assets_empty_call_grpc_asyncio(): + client = LivestreamServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.list_assets), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + service.ListAssetsResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], + ) + ) + await client.list_assets(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.ListAssetsRequest() + + assert args[0] == request_msg + + +# This test is a coverage 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_pool_empty_call_grpc_asyncio(): + client = LivestreamServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_pool), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + resources.Pool( + name="name_value", + ) + ) + await client.get_pool(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.GetPoolRequest() + + assert args[0] == request_msg + + +# This test is a coverage 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_pool_empty_call_grpc_asyncio(): + client = LivestreamServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.update_pool), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + await client.update_pool(request=None) # Establish that the underlying stub method was called. call.assert_called() _, args, _ = call.mock_calls[0] - request_msg = service.GetEventRequest() + request_msg = service.UpdatePoolRequest() + + assert args[0] == request_msg + + +def test_transport_kind_rest(): + transport = LivestreamServiceClient.get_transport_class("rest")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "rest" + + +def test_create_channel_rest_bad_request(request_type=service.CreateChannelRequest): + client = LivestreamServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.create_channel(request) + + +@pytest.mark.parametrize( + "request_type", + [ + service.CreateChannelRequest, + dict, + ], +) +def test_create_channel_rest_call_success(request_type): + client = LivestreamServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2"} + request_init["channel"] = { + "name": "name_value", + "create_time": {"seconds": 751, "nanos": 543}, + "update_time": {}, + "labels": {}, + "input_attachments": [ + { + "key": "key_value", + "input": "input_value", + "automatic_failover": { + "input_keys": ["input_keys_value1", "input_keys_value2"] + }, + } + ], + "active_input": "active_input_value", + "output": {"uri": "uri_value"}, + "elementary_streams": [ + { + "key": "key_value", + "video_stream": { + "h264": { + "width_pixels": 1300, + "height_pixels": 1389, + "frame_rate": 0.1046, + "bitrate_bps": 1167, + "allow_open_gop": True, + "gop_frame_count": 1592, + "gop_duration": {"seconds": 751, "nanos": 543}, + "vbv_size_bits": 1401, + "vbv_fullness_bits": 1834, + "entropy_coder": "entropy_coder_value", + "b_pyramid": True, + "b_frame_count": 1364, + "aq_strength": 0.1184, + "profile": "profile_value", + "tune": "tune_value", + } + }, + "audio_stream": { + "transmux": True, + "codec": "codec_value", + "bitrate_bps": 1167, + "channel_count": 1377, + "channel_layout": [ + "channel_layout_value1", + "channel_layout_value2", + ], + "mapping_": [ + { + "input_key": "input_key_value", + "input_track": 1188, + "input_channel": 1384, + "output_channel": 1513, + "gain_db": 0.708, + } + ], + "sample_rate_hertz": 1817, + }, + "text_stream": {"codec": "codec_value"}, + } + ], + "mux_streams": [ + { + "key": "key_value", + "container": "container_value", + "elementary_streams": [ + "elementary_streams_value1", + "elementary_streams_value2", + ], + "segment_settings": {"segment_duration": {}}, + "encryption_id": "encryption_id_value", + } + ], + "manifests": [ + { + "file_name": "file_name_value", + "type_": 1, + "mux_streams": ["mux_streams_value1", "mux_streams_value2"], + "max_segment_count": 1824, + "segment_keep_duration": {}, + "use_timecode_as_timeline": True, + "key": "key_value", + } + ], + "sprite_sheets": [ + { + "format_": "format__value", + "file_prefix": "file_prefix_value", + "sprite_width_pixels": 2058, + "sprite_height_pixels": 2147, + "column_count": 1302, + "row_count": 992, + "interval": {}, + "quality": 777, + } + ], + "streaming_state": 1, + "streaming_error": { + "code": 411, + "message": "message_value", + "details": [ + { + "type_url": "type.googleapis.com/google.protobuf.Duration", + "value": b"\x08\x0c\x10\xdb\x07", + } + ], + }, + "log_config": {"log_severity": 1}, + "timecode_config": { + "source": 1, + "utc_offset": {}, + "time_zone": {"id": "id_value", "version": "version_value"}, + }, + "encryptions": [ + { + "id": "id_value", + "secret_manager_key_source": {"secret_version": "secret_version_value"}, + "drm_systems": { + "widevine": {}, + "fairplay": {}, + "playready": {}, + "clearkey": {}, + }, + "aes128": {}, + "sample_aes": {}, + "mpeg_cenc": {"scheme": "scheme_value"}, + } + ], + "input_config": {"input_switch_mode": 1}, + "retention_config": {"retention_window_duration": {}}, + "static_overlays": [ + { + "asset": "asset_value", + "resolution": {"w": 0.11900000000000001, "h": 0.10400000000000001}, + "position": {"x": 0.12, "y": 0.121}, + "opacity": 0.761, + } + ], + } + # 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 = service.CreateChannelRequest.meta.fields["channel"] + + 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["channel"].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["channel"][field])): + del request_init["channel"][field][i][subfield] + else: + del request_init["channel"][field][subfield] + request = request_type(**request_init) - assert args[0] == request_msg + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.create_channel(request) -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -@pytest.mark.asyncio -async def test_delete_event_empty_call_grpc_asyncio(): - client = LivestreamServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) - # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.delete_event), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.delete_event(request=None) - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = service.DeleteEventRequest() +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_channel_rest_interceptors(null_interceptor): + transport = transports.LivestreamServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.LivestreamServiceRestInterceptor(), + ) + client = LivestreamServiceClient(transport=transport) - assert args[0] == request_msg + 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.LivestreamServiceRestInterceptor, "post_create_channel" + ) as post, mock.patch.object( + transports.LivestreamServiceRestInterceptor, "post_create_channel_with_metadata" + ) as post_with_metadata, mock.patch.object( + transports.LivestreamServiceRestInterceptor, "pre_create_channel" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = service.CreateChannelRequest.pb(service.CreateChannelRequest()) + 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 -# This test is a coverage 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_clips_empty_call_grpc_asyncio(): - client = LivestreamServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) + request = service.CreateChannelRequest() + 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 - # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.list_clips), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - service.ListClipsResponse( - next_page_token="next_page_token_value", - unreachable=["unreachable_value"], - ) + client.create_channel( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], ) - await client.list_clips(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = service.ListClipsRequest() - assert args[0] == request_msg + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -@pytest.mark.asyncio -async def test_get_clip_empty_call_grpc_asyncio(): - client = LivestreamServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", +def test_list_channels_rest_bad_request(request_type=service.ListChannelsRequest): + client = LivestreamServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2"} + request = request_type(**request_init) - # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.get_clip), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - resources.Clip( - name="name_value", - state=resources.Clip.State.PENDING, - output_uri="output_uri_value", - ) - ) - await client.get_clip(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = service.GetClipRequest() - - assert args[0] == request_msg + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.list_channels(request) -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -@pytest.mark.asyncio -async def test_create_clip_empty_call_grpc_asyncio(): - client = LivestreamServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", +@pytest.mark.parametrize( + "request_type", + [ + service.ListChannelsRequest, + dict, + ], +) +def test_list_channels_rest_call_success(request_type): + client = LivestreamServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) - # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.create_clip), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = service.ListChannelsResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], ) - await client.create_clip(request=None) - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = service.CreateClipRequest() + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 - assert args[0] == request_msg + # Convert return value to protobuf type + return_value = service.ListChannelsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_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_channels(request) + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListChannelsPager) + assert response.next_page_token == "next_page_token_value" + assert response.unreachable == ["unreachable_value"] -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -@pytest.mark.asyncio -async def test_delete_clip_empty_call_grpc_asyncio(): - client = LivestreamServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_channels_rest_interceptors(null_interceptor): + transport = transports.LivestreamServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.LivestreamServiceRestInterceptor(), ) + client = LivestreamServiceClient(transport=transport) - # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.delete_clip), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") - ) - await client.delete_clip(request=None) + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.LivestreamServiceRestInterceptor, "post_list_channels" + ) as post, mock.patch.object( + transports.LivestreamServiceRestInterceptor, "post_list_channels_with_metadata" + ) as post_with_metadata, mock.patch.object( + transports.LivestreamServiceRestInterceptor, "pre_list_channels" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = service.ListChannelsRequest.pb(service.ListChannelsRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = service.DeleteClipRequest() + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = service.ListChannelsResponse.to_json( + service.ListChannelsResponse() + ) + req.return_value.content = return_value - assert args[0] == request_msg + request = service.ListChannelsRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = service.ListChannelsResponse() + post_with_metadata.return_value = service.ListChannelsResponse(), metadata + client.list_channels( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -@pytest.mark.asyncio -async def test_create_asset_empty_call_grpc_asyncio(): - client = LivestreamServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() - # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.create_asset), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") - ) - await client.create_asset(request=None) - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = service.CreateAssetRequest() +def test_get_channel_rest_bad_request(request_type=service.GetChannelRequest): + client = LivestreamServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/channels/sample3"} + request = request_type(**request_init) - assert args[0] == request_msg + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.get_channel(request) -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -@pytest.mark.asyncio -async def test_delete_asset_empty_call_grpc_asyncio(): - client = LivestreamServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", +@pytest.mark.parametrize( + "request_type", + [ + service.GetChannelRequest, + dict, + ], +) +def test_get_channel_rest_call_success(request_type): + client = LivestreamServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) - # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.delete_asset), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/channels/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 = resources.Channel( + name="name_value", + active_input="active_input_value", + streaming_state=resources.Channel.StreamingState.STREAMING, ) - await client.delete_asset(request=None) - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = service.DeleteAssetRequest() + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 - assert args[0] == request_msg + # Convert return value to protobuf type + return_value = resources.Channel.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_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_channel(request) + # Establish that the response is the type that we expect. + assert isinstance(response, resources.Channel) + assert response.name == "name_value" + assert response.active_input == "active_input_value" + assert response.streaming_state == resources.Channel.StreamingState.STREAMING -# This test is a coverage 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_asset_empty_call_grpc_asyncio(): - client = LivestreamServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_channel_rest_interceptors(null_interceptor): + transport = transports.LivestreamServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.LivestreamServiceRestInterceptor(), ) + client = LivestreamServiceClient(transport=transport) - # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.get_asset), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - resources.Asset( - name="name_value", - crc32c="crc32c_value", - state=resources.Asset.State.CREATING, - ) - ) - await client.get_asset(request=None) + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.LivestreamServiceRestInterceptor, "post_get_channel" + ) as post, mock.patch.object( + transports.LivestreamServiceRestInterceptor, "post_get_channel_with_metadata" + ) as post_with_metadata, mock.patch.object( + transports.LivestreamServiceRestInterceptor, "pre_get_channel" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = service.GetChannelRequest.pb(service.GetChannelRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = service.GetAssetRequest() + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = resources.Channel.to_json(resources.Channel()) + req.return_value.content = return_value - assert args[0] == request_msg + request = service.GetChannelRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = resources.Channel() + post_with_metadata.return_value = resources.Channel(), metadata + client.get_channel( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -@pytest.mark.asyncio -async def test_list_assets_empty_call_grpc_asyncio(): - client = LivestreamServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() - # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.list_assets), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - service.ListAssetsResponse( - next_page_token="next_page_token_value", - unreachable=["unreachable_value"], - ) - ) - await client.list_assets(request=None) - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = service.ListAssetsRequest() +def test_delete_channel_rest_bad_request(request_type=service.DeleteChannelRequest): + client = LivestreamServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/channels/sample3"} + request = request_type(**request_init) - assert args[0] == request_msg + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.delete_channel(request) -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -@pytest.mark.asyncio -async def test_get_pool_empty_call_grpc_asyncio(): - client = LivestreamServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", +@pytest.mark.parametrize( + "request_type", + [ + service.DeleteChannelRequest, + dict, + ], +) +def test_delete_channel_rest_call_success(request_type): + client = LivestreamServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) - # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.get_pool), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - resources.Pool( - name="name_value", - ) - ) - await client.get_pool(request=None) + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/channels/sample3"} + request = request_type(**request_init) - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = service.GetPoolRequest() + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") - assert args[0] == request_msg + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.delete_channel(request) + # Establish that the response is the type that we expect. + 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_pool_empty_call_grpc_asyncio(): - client = LivestreamServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_channel_rest_interceptors(null_interceptor): + transport = transports.LivestreamServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.LivestreamServiceRestInterceptor(), ) + client = LivestreamServiceClient(transport=transport) - # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.update_pool), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") - ) - await client.update_pool(request=None) + 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.LivestreamServiceRestInterceptor, "post_delete_channel" + ) as post, mock.patch.object( + transports.LivestreamServiceRestInterceptor, "post_delete_channel_with_metadata" + ) as post_with_metadata, mock.patch.object( + transports.LivestreamServiceRestInterceptor, "pre_delete_channel" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = service.DeleteChannelRequest.pb(service.DeleteChannelRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = service.UpdatePoolRequest() + req.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 - assert args[0] == request_msg + request = service.DeleteChannelRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + post_with_metadata.return_value = operations_pb2.Operation(), metadata + client.delete_channel( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) -def test_transport_kind_rest(): - transport = LivestreamServiceClient.get_transport_class("rest")( - credentials=ga_credentials.AnonymousCredentials() - ) - assert transport.kind == "rest" + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() -def test_create_channel_rest_bad_request(request_type=service.CreateChannelRequest): +def test_update_channel_rest_bad_request(request_type=service.UpdateChannelRequest): client = LivestreamServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/locations/sample2"} + request_init = { + "channel": {"name": "projects/sample1/locations/sample2/channels/sample3"} + } request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -17410,25 +21362,27 @@ def test_create_channel_rest_bad_request(request_type=service.CreateChannelReque response_value.request = mock.Mock() req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.create_channel(request) + client.update_channel(request) @pytest.mark.parametrize( "request_type", [ - service.CreateChannelRequest, + service.UpdateChannelRequest, dict, ], ) -def test_create_channel_rest_call_success(request_type): +def test_update_channel_rest_call_success(request_type): client = LivestreamServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/locations/sample2"} + request_init = { + "channel": {"name": "projects/sample1/locations/sample2/channels/sample3"} + } request_init["channel"] = { - "name": "name_value", + "name": "projects/sample1/locations/sample2/channels/sample3", "create_time": {"seconds": 751, "nanos": 543}, "update_time": {}, "labels": {}, @@ -17571,7 +21525,7 @@ def test_create_channel_rest_call_success(request_type): # See https://github.com/googleapis/gapic-generator-python/issues/1748 # Determine if the message type is proto-plus or protobuf - test_field = service.CreateChannelRequest.meta.fields["channel"] + test_field = service.UpdateChannelRequest.meta.fields["channel"] def get_message_fields(field): # Given a field which is a message (composite type), return a list with @@ -17647,14 +21601,133 @@ def get_message_fields(field): response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.create_channel(request) + response = client.update_channel(request) # Establish that the response is the type that we expect. json_return_value = json_format.MessageToJson(return_value) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_create_channel_rest_interceptors(null_interceptor): +def test_update_channel_rest_interceptors(null_interceptor): + transport = transports.LivestreamServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.LivestreamServiceRestInterceptor(), + ) + client = LivestreamServiceClient(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.LivestreamServiceRestInterceptor, "post_update_channel" + ) as post, mock.patch.object( + transports.LivestreamServiceRestInterceptor, "post_update_channel_with_metadata" + ) as post_with_metadata, mock.patch.object( + transports.LivestreamServiceRestInterceptor, "pre_update_channel" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = service.UpdateChannelRequest.pb(service.UpdateChannelRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = service.UpdateChannelRequest() + 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_channel( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_start_channel_rest_bad_request(request_type=service.StartChannelRequest): + client = LivestreamServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/channels/sample3"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.start_channel(request) + + +@pytest.mark.parametrize( + "request_type", + [ + service.StartChannelRequest, + dict, + ], +) +def test_start_channel_rest_call_success(request_type): + client = LivestreamServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/channels/sample3"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.start_channel(request) + + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_start_channel_rest_interceptors(null_interceptor): transport = transports.LivestreamServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -17670,16 +21743,16 @@ def test_create_channel_rest_interceptors(null_interceptor): ) as transcode, mock.patch.object( operation.Operation, "_set_result_from_operation" ), mock.patch.object( - transports.LivestreamServiceRestInterceptor, "post_create_channel" + transports.LivestreamServiceRestInterceptor, "post_start_channel" ) as post, mock.patch.object( - transports.LivestreamServiceRestInterceptor, "post_create_channel_with_metadata" + transports.LivestreamServiceRestInterceptor, "post_start_channel_with_metadata" ) as post_with_metadata, mock.patch.object( - transports.LivestreamServiceRestInterceptor, "pre_create_channel" + transports.LivestreamServiceRestInterceptor, "pre_start_channel" ) as pre: pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = service.CreateChannelRequest.pb(service.CreateChannelRequest()) + pb_message = service.StartChannelRequest.pb(service.StartChannelRequest()) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -17693,7 +21766,7 @@ def test_create_channel_rest_interceptors(null_interceptor): return_value = json_format.MessageToJson(operations_pb2.Operation()) req.return_value.content = return_value - request = service.CreateChannelRequest() + request = service.StartChannelRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), @@ -17702,7 +21775,7 @@ def test_create_channel_rest_interceptors(null_interceptor): post.return_value = operations_pb2.Operation() post_with_metadata.return_value = operations_pb2.Operation(), metadata - client.create_channel( + client.start_channel( request, metadata=[ ("key", "val"), @@ -17715,12 +21788,12 @@ def test_create_channel_rest_interceptors(null_interceptor): post_with_metadata.assert_called_once() -def test_list_channels_rest_bad_request(request_type=service.ListChannelsRequest): +def test_stop_channel_rest_bad_request(request_type=service.StopChannelRequest): client = LivestreamServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/locations/sample2"} + request_init = {"name": "projects/sample1/locations/sample2/channels/sample3"} request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -17735,53 +21808,45 @@ def test_list_channels_rest_bad_request(request_type=service.ListChannelsRequest response_value.request = mock.Mock() req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.list_channels(request) + client.stop_channel(request) @pytest.mark.parametrize( "request_type", [ - service.ListChannelsRequest, + service.StopChannelRequest, dict, ], ) -def test_list_channels_rest_call_success(request_type): +def test_stop_channel_rest_call_success(request_type): client = LivestreamServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/locations/sample2"} + request_init = {"name": "projects/sample1/locations/sample2/channels/sample3"} request = request_type(**request_init) # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = service.ListChannelsResponse( - 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 = service.ListChannelsResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value.content = json_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_channels(request) + response = client.stop_channel(request) # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListChannelsPager) - 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_channels_rest_interceptors(null_interceptor): +def test_stop_channel_rest_interceptors(null_interceptor): transport = transports.LivestreamServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -17795,16 +21860,18 @@ def test_list_channels_rest_interceptors(null_interceptor): ) as req, mock.patch.object( path_template, "transcode" ) as transcode, mock.patch.object( - transports.LivestreamServiceRestInterceptor, "post_list_channels" + operation.Operation, "_set_result_from_operation" + ), mock.patch.object( + transports.LivestreamServiceRestInterceptor, "post_stop_channel" ) as post, mock.patch.object( - transports.LivestreamServiceRestInterceptor, "post_list_channels_with_metadata" + transports.LivestreamServiceRestInterceptor, "post_stop_channel_with_metadata" ) as post_with_metadata, mock.patch.object( - transports.LivestreamServiceRestInterceptor, "pre_list_channels" + transports.LivestreamServiceRestInterceptor, "pre_stop_channel" ) as pre: pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = service.ListChannelsRequest.pb(service.ListChannelsRequest()) + pb_message = service.StopChannelRequest.pb(service.StopChannelRequest()) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -17815,21 +21882,19 @@ def test_list_channels_rest_interceptors(null_interceptor): req.return_value = mock.Mock() req.return_value.status_code = 200 req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - return_value = service.ListChannelsResponse.to_json( - service.ListChannelsResponse() - ) + return_value = json_format.MessageToJson(operations_pb2.Operation()) req.return_value.content = return_value - request = service.ListChannelsRequest() + request = service.StopChannelRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = service.ListChannelsResponse() - post_with_metadata.return_value = service.ListChannelsResponse(), metadata + post.return_value = operations_pb2.Operation() + post_with_metadata.return_value = operations_pb2.Operation(), metadata - client.list_channels( + client.stop_channel( request, metadata=[ ("key", "val"), @@ -17842,12 +21907,12 @@ def test_list_channels_rest_interceptors(null_interceptor): post_with_metadata.assert_called_once() -def test_get_channel_rest_bad_request(request_type=service.GetChannelRequest): +def test_create_input_rest_bad_request(request_type=service.CreateInputRequest): client = LivestreamServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/locations/sample2/channels/sample3"} + request_init = {"parent": "projects/sample1/locations/sample2"} request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -17862,55 +21927,164 @@ def test_get_channel_rest_bad_request(request_type=service.GetChannelRequest): response_value.request = mock.Mock() req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.get_channel(request) + client.create_input(request) @pytest.mark.parametrize( "request_type", [ - service.GetChannelRequest, + service.CreateInputRequest, dict, ], ) -def test_get_channel_rest_call_success(request_type): +def test_create_input_rest_call_success(request_type): client = LivestreamServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/locations/sample2/channels/sample3"} + request_init = {"parent": "projects/sample1/locations/sample2"} + request_init["input"] = { + "name": "name_value", + "create_time": {"seconds": 751, "nanos": 543}, + "update_time": {}, + "labels": {}, + "type_": 1, + "tier": 1, + "uri": "uri_value", + "preprocessing_config": { + "audio": {"lufs": 0.442}, + "crop": { + "top_pixels": 1095, + "bottom_pixels": 1417, + "left_pixels": 1183, + "right_pixels": 1298, + }, + "pad": { + "top_pixels": 1095, + "bottom_pixels": 1417, + "left_pixels": 1183, + "right_pixels": 1298, + }, + }, + "security_rules": {"ip_ranges": ["ip_ranges_value1", "ip_ranges_value2"]}, + "input_stream_property": { + "last_establish_time": {}, + "video_streams": [ + { + "index": 536, + "video_format": { + "codec": "codec_value", + "width_pixels": 1300, + "height_pixels": 1389, + "frame_rate": 0.1046, + }, + } + ], + "audio_streams": [ + { + "index": 536, + "audio_format": { + "codec": "codec_value", + "channel_count": 1377, + "channel_layout": [ + "channel_layout_value1", + "channel_layout_value2", + ], + }, + } + ], + }, + } + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = service.CreateInputRequest.meta.fields["input"] + + 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["input"].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["input"][field])): + del request_init["input"][field][i][subfield] + else: + del request_init["input"][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 = resources.Channel( - name="name_value", - active_input="active_input_value", - streaming_state=resources.Channel.StreamingState.STREAMING, - ) + 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 = resources.Channel.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value.content = json_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_channel(request) + response = client.create_input(request) # Establish that the response is the type that we expect. - assert isinstance(response, resources.Channel) - assert response.name == "name_value" - assert response.active_input == "active_input_value" - assert response.streaming_state == resources.Channel.StreamingState.STREAMING + json_return_value = json_format.MessageToJson(return_value) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_channel_rest_interceptors(null_interceptor): +def test_create_input_rest_interceptors(null_interceptor): transport = transports.LivestreamServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -17924,16 +22098,18 @@ def test_get_channel_rest_interceptors(null_interceptor): ) as req, mock.patch.object( path_template, "transcode" ) as transcode, mock.patch.object( - transports.LivestreamServiceRestInterceptor, "post_get_channel" + operation.Operation, "_set_result_from_operation" + ), mock.patch.object( + transports.LivestreamServiceRestInterceptor, "post_create_input" ) as post, mock.patch.object( - transports.LivestreamServiceRestInterceptor, "post_get_channel_with_metadata" + transports.LivestreamServiceRestInterceptor, "post_create_input_with_metadata" ) as post_with_metadata, mock.patch.object( - transports.LivestreamServiceRestInterceptor, "pre_get_channel" + transports.LivestreamServiceRestInterceptor, "pre_create_input" ) as pre: pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = service.GetChannelRequest.pb(service.GetChannelRequest()) + pb_message = service.CreateInputRequest.pb(service.CreateInputRequest()) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -17944,19 +22120,19 @@ def test_get_channel_rest_interceptors(null_interceptor): req.return_value = mock.Mock() req.return_value.status_code = 200 req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - return_value = resources.Channel.to_json(resources.Channel()) + return_value = json_format.MessageToJson(operations_pb2.Operation()) req.return_value.content = return_value - request = service.GetChannelRequest() + request = service.CreateInputRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = resources.Channel() - post_with_metadata.return_value = resources.Channel(), metadata + post.return_value = operations_pb2.Operation() + post_with_metadata.return_value = operations_pb2.Operation(), metadata - client.get_channel( + client.create_input( request, metadata=[ ("key", "val"), @@ -17969,12 +22145,12 @@ def test_get_channel_rest_interceptors(null_interceptor): post_with_metadata.assert_called_once() -def test_delete_channel_rest_bad_request(request_type=service.DeleteChannelRequest): +def test_list_inputs_rest_bad_request(request_type=service.ListInputsRequest): client = LivestreamServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/locations/sample2/channels/sample3"} + request_init = {"parent": "projects/sample1/locations/sample2"} request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -17989,45 +22165,53 @@ def test_delete_channel_rest_bad_request(request_type=service.DeleteChannelReque response_value.request = mock.Mock() req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.delete_channel(request) + client.list_inputs(request) @pytest.mark.parametrize( "request_type", [ - service.DeleteChannelRequest, + service.ListInputsRequest, dict, ], ) -def test_delete_channel_rest_call_success(request_type): +def test_list_inputs_rest_call_success(request_type): client = LivestreamServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/locations/sample2/channels/sample3"} + request_init = {"parent": "projects/sample1/locations/sample2"} request = request_type(**request_init) # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name="operations/spam") + return_value = service.ListInputsResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], + ) # Wrap the value into a proper Response obj response_value = mock.Mock() response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = service.ListInputsResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value.content = json_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_channel(request) + response = client.list_inputs(request) # Establish that the response is the type that we expect. - json_return_value = json_format.MessageToJson(return_value) + assert isinstance(response, pagers.ListInputsPager) + assert response.next_page_token == "next_page_token_value" + assert response.unreachable == ["unreachable_value"] @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_delete_channel_rest_interceptors(null_interceptor): +def test_list_inputs_rest_interceptors(null_interceptor): transport = transports.LivestreamServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -18041,18 +22225,16 @@ def test_delete_channel_rest_interceptors(null_interceptor): ) as req, mock.patch.object( path_template, "transcode" ) as transcode, mock.patch.object( - operation.Operation, "_set_result_from_operation" - ), mock.patch.object( - transports.LivestreamServiceRestInterceptor, "post_delete_channel" + transports.LivestreamServiceRestInterceptor, "post_list_inputs" ) as post, mock.patch.object( - transports.LivestreamServiceRestInterceptor, "post_delete_channel_with_metadata" + transports.LivestreamServiceRestInterceptor, "post_list_inputs_with_metadata" ) as post_with_metadata, mock.patch.object( - transports.LivestreamServiceRestInterceptor, "pre_delete_channel" + transports.LivestreamServiceRestInterceptor, "pre_list_inputs" ) as pre: pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = service.DeleteChannelRequest.pb(service.DeleteChannelRequest()) + pb_message = service.ListInputsRequest.pb(service.ListInputsRequest()) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -18063,19 +22245,19 @@ def test_delete_channel_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 = service.ListInputsResponse.to_json(service.ListInputsResponse()) req.return_value.content = return_value - request = service.DeleteChannelRequest() + request = service.ListInputsRequest() 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 = service.ListInputsResponse() + post_with_metadata.return_value = service.ListInputsResponse(), metadata - client.delete_channel( + client.list_inputs( request, metadata=[ ("key", "val"), @@ -18088,14 +22270,12 @@ def test_delete_channel_rest_interceptors(null_interceptor): post_with_metadata.assert_called_once() -def test_update_channel_rest_bad_request(request_type=service.UpdateChannelRequest): +def test_get_input_rest_bad_request(request_type=service.GetInputRequest): client = LivestreamServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = { - "channel": {"name": "projects/sample1/locations/sample2/channels/sample3"} - } + request_init = {"name": "projects/sample1/locations/sample2/inputs/sample3"} request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -18110,253 +22290,57 @@ def test_update_channel_rest_bad_request(request_type=service.UpdateChannelReque response_value.request = mock.Mock() req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.update_channel(request) + client.get_input(request) @pytest.mark.parametrize( "request_type", [ - service.UpdateChannelRequest, + service.GetInputRequest, dict, ], ) -def test_update_channel_rest_call_success(request_type): +def test_get_input_rest_call_success(request_type): client = LivestreamServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = { - "channel": {"name": "projects/sample1/locations/sample2/channels/sample3"} - } - request_init["channel"] = { - "name": "projects/sample1/locations/sample2/channels/sample3", - "create_time": {"seconds": 751, "nanos": 543}, - "update_time": {}, - "labels": {}, - "input_attachments": [ - { - "key": "key_value", - "input": "input_value", - "automatic_failover": { - "input_keys": ["input_keys_value1", "input_keys_value2"] - }, - } - ], - "active_input": "active_input_value", - "output": {"uri": "uri_value"}, - "elementary_streams": [ - { - "key": "key_value", - "video_stream": { - "h264": { - "width_pixels": 1300, - "height_pixels": 1389, - "frame_rate": 0.1046, - "bitrate_bps": 1167, - "allow_open_gop": True, - "gop_frame_count": 1592, - "gop_duration": {"seconds": 751, "nanos": 543}, - "vbv_size_bits": 1401, - "vbv_fullness_bits": 1834, - "entropy_coder": "entropy_coder_value", - "b_pyramid": True, - "b_frame_count": 1364, - "aq_strength": 0.1184, - "profile": "profile_value", - "tune": "tune_value", - } - }, - "audio_stream": { - "transmux": True, - "codec": "codec_value", - "bitrate_bps": 1167, - "channel_count": 1377, - "channel_layout": [ - "channel_layout_value1", - "channel_layout_value2", - ], - "mapping_": [ - { - "input_key": "input_key_value", - "input_track": 1188, - "input_channel": 1384, - "output_channel": 1513, - "gain_db": 0.708, - } - ], - "sample_rate_hertz": 1817, - }, - "text_stream": {"codec": "codec_value"}, - } - ], - "mux_streams": [ - { - "key": "key_value", - "container": "container_value", - "elementary_streams": [ - "elementary_streams_value1", - "elementary_streams_value2", - ], - "segment_settings": {"segment_duration": {}}, - "encryption_id": "encryption_id_value", - } - ], - "manifests": [ - { - "file_name": "file_name_value", - "type_": 1, - "mux_streams": ["mux_streams_value1", "mux_streams_value2"], - "max_segment_count": 1824, - "segment_keep_duration": {}, - "use_timecode_as_timeline": True, - "key": "key_value", - } - ], - "sprite_sheets": [ - { - "format_": "format__value", - "file_prefix": "file_prefix_value", - "sprite_width_pixels": 2058, - "sprite_height_pixels": 2147, - "column_count": 1302, - "row_count": 992, - "interval": {}, - "quality": 777, - } - ], - "streaming_state": 1, - "streaming_error": { - "code": 411, - "message": "message_value", - "details": [ - { - "type_url": "type.googleapis.com/google.protobuf.Duration", - "value": b"\x08\x0c\x10\xdb\x07", - } - ], - }, - "log_config": {"log_severity": 1}, - "timecode_config": { - "source": 1, - "utc_offset": {}, - "time_zone": {"id": "id_value", "version": "version_value"}, - }, - "encryptions": [ - { - "id": "id_value", - "secret_manager_key_source": {"secret_version": "secret_version_value"}, - "drm_systems": { - "widevine": {}, - "fairplay": {}, - "playready": {}, - "clearkey": {}, - }, - "aes128": {}, - "sample_aes": {}, - "mpeg_cenc": {"scheme": "scheme_value"}, - } - ], - "input_config": {"input_switch_mode": 1}, - "retention_config": {"retention_window_duration": {}}, - "static_overlays": [ - { - "asset": "asset_value", - "resolution": {"w": 0.11900000000000001, "h": 0.10400000000000001}, - "position": {"x": 0.12, "y": 0.121}, - "opacity": 0.761, - } - ], - } - # 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 = service.UpdateChannelRequest.meta.fields["channel"] - - 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["channel"].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["channel"][field])): - del request_init["channel"][field][i][subfield] - else: - del request_init["channel"][field][subfield] + request_init = {"name": "projects/sample1/locations/sample2/inputs/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 = resources.Input( + name="name_value", + type_=resources.Input.Type.RTMP_PUSH, + tier=resources.Input.Tier.SD, + uri="uri_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 = resources.Input.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value.content = json_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_channel(request) + response = client.get_input(request) # Establish that the response is the type that we expect. - json_return_value = json_format.MessageToJson(return_value) + assert isinstance(response, resources.Input) + assert response.name == "name_value" + assert response.type_ == resources.Input.Type.RTMP_PUSH + assert response.tier == resources.Input.Tier.SD + assert response.uri == "uri_value" @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_update_channel_rest_interceptors(null_interceptor): +def test_get_input_rest_interceptors(null_interceptor): transport = transports.LivestreamServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -18370,18 +22354,16 @@ def test_update_channel_rest_interceptors(null_interceptor): ) as req, mock.patch.object( path_template, "transcode" ) as transcode, mock.patch.object( - operation.Operation, "_set_result_from_operation" - ), mock.patch.object( - transports.LivestreamServiceRestInterceptor, "post_update_channel" + transports.LivestreamServiceRestInterceptor, "post_get_input" ) as post, mock.patch.object( - transports.LivestreamServiceRestInterceptor, "post_update_channel_with_metadata" + transports.LivestreamServiceRestInterceptor, "post_get_input_with_metadata" ) as post_with_metadata, mock.patch.object( - transports.LivestreamServiceRestInterceptor, "pre_update_channel" + transports.LivestreamServiceRestInterceptor, "pre_get_input" ) as pre: pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = service.UpdateChannelRequest.pb(service.UpdateChannelRequest()) + pb_message = service.GetInputRequest.pb(service.GetInputRequest()) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -18392,19 +22374,19 @@ def test_update_channel_rest_interceptors(null_interceptor): req.return_value = mock.Mock() req.return_value.status_code = 200 req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - return_value = json_format.MessageToJson(operations_pb2.Operation()) + return_value = resources.Input.to_json(resources.Input()) req.return_value.content = return_value - request = service.UpdateChannelRequest() + request = service.GetInputRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - post_with_metadata.return_value = operations_pb2.Operation(), metadata + post.return_value = resources.Input() + post_with_metadata.return_value = resources.Input(), metadata - client.update_channel( + client.get_input( request, metadata=[ ("key", "val"), @@ -18417,12 +22399,12 @@ def test_update_channel_rest_interceptors(null_interceptor): post_with_metadata.assert_called_once() -def test_start_channel_rest_bad_request(request_type=service.StartChannelRequest): +def test_delete_input_rest_bad_request(request_type=service.DeleteInputRequest): client = LivestreamServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/locations/sample2/channels/sample3"} + request_init = {"name": "projects/sample1/locations/sample2/inputs/sample3"} request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -18437,23 +22419,23 @@ def test_start_channel_rest_bad_request(request_type=service.StartChannelRequest response_value.request = mock.Mock() req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.start_channel(request) + client.delete_input(request) @pytest.mark.parametrize( "request_type", [ - service.StartChannelRequest, + service.DeleteInputRequest, dict, ], ) -def test_start_channel_rest_call_success(request_type): +def test_delete_input_rest_call_success(request_type): client = LivestreamServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/locations/sample2/channels/sample3"} + request_init = {"name": "projects/sample1/locations/sample2/inputs/sample3"} request = request_type(**request_init) # Mock the http request call within the method and fake a response. @@ -18468,14 +22450,14 @@ def test_start_channel_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.start_channel(request) + response = client.delete_input(request) # Establish that the response is the type that we expect. json_return_value = json_format.MessageToJson(return_value) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_start_channel_rest_interceptors(null_interceptor): +def test_delete_input_rest_interceptors(null_interceptor): transport = transports.LivestreamServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -18491,16 +22473,16 @@ def test_start_channel_rest_interceptors(null_interceptor): ) as transcode, mock.patch.object( operation.Operation, "_set_result_from_operation" ), mock.patch.object( - transports.LivestreamServiceRestInterceptor, "post_start_channel" + transports.LivestreamServiceRestInterceptor, "post_delete_input" ) as post, mock.patch.object( - transports.LivestreamServiceRestInterceptor, "post_start_channel_with_metadata" + transports.LivestreamServiceRestInterceptor, "post_delete_input_with_metadata" ) as post_with_metadata, mock.patch.object( - transports.LivestreamServiceRestInterceptor, "pre_start_channel" + transports.LivestreamServiceRestInterceptor, "pre_delete_input" ) as pre: pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = service.StartChannelRequest.pb(service.StartChannelRequest()) + pb_message = service.DeleteInputRequest.pb(service.DeleteInputRequest()) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -18514,7 +22496,7 @@ def test_start_channel_rest_interceptors(null_interceptor): return_value = json_format.MessageToJson(operations_pb2.Operation()) req.return_value.content = return_value - request = service.StartChannelRequest() + request = service.DeleteInputRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), @@ -18523,7 +22505,7 @@ def test_start_channel_rest_interceptors(null_interceptor): post.return_value = operations_pb2.Operation() post_with_metadata.return_value = operations_pb2.Operation(), metadata - client.start_channel( + client.delete_input( request, metadata=[ ("key", "val"), @@ -18536,12 +22518,14 @@ def test_start_channel_rest_interceptors(null_interceptor): post_with_metadata.assert_called_once() -def test_stop_channel_rest_bad_request(request_type=service.StopChannelRequest): +def test_update_input_rest_bad_request(request_type=service.UpdateInputRequest): client = LivestreamServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/locations/sample2/channels/sample3"} + request_init = { + "input": {"name": "projects/sample1/locations/sample2/inputs/sample3"} + } request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -18556,23 +22540,144 @@ def test_stop_channel_rest_bad_request(request_type=service.StopChannelRequest): response_value.request = mock.Mock() req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.stop_channel(request) + client.update_input(request) @pytest.mark.parametrize( "request_type", [ - service.StopChannelRequest, + service.UpdateInputRequest, dict, ], ) -def test_stop_channel_rest_call_success(request_type): +def test_update_input_rest_call_success(request_type): client = LivestreamServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/locations/sample2/channels/sample3"} + request_init = { + "input": {"name": "projects/sample1/locations/sample2/inputs/sample3"} + } + request_init["input"] = { + "name": "projects/sample1/locations/sample2/inputs/sample3", + "create_time": {"seconds": 751, "nanos": 543}, + "update_time": {}, + "labels": {}, + "type_": 1, + "tier": 1, + "uri": "uri_value", + "preprocessing_config": { + "audio": {"lufs": 0.442}, + "crop": { + "top_pixels": 1095, + "bottom_pixels": 1417, + "left_pixels": 1183, + "right_pixels": 1298, + }, + "pad": { + "top_pixels": 1095, + "bottom_pixels": 1417, + "left_pixels": 1183, + "right_pixels": 1298, + }, + }, + "security_rules": {"ip_ranges": ["ip_ranges_value1", "ip_ranges_value2"]}, + "input_stream_property": { + "last_establish_time": {}, + "video_streams": [ + { + "index": 536, + "video_format": { + "codec": "codec_value", + "width_pixels": 1300, + "height_pixels": 1389, + "frame_rate": 0.1046, + }, + } + ], + "audio_streams": [ + { + "index": 536, + "audio_format": { + "codec": "codec_value", + "channel_count": 1377, + "channel_layout": [ + "channel_layout_value1", + "channel_layout_value2", + ], + }, + } + ], + }, + } + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = service.UpdateInputRequest.meta.fields["input"] + + 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["input"].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["input"][field])): + del request_init["input"][field][i][subfield] + else: + del request_init["input"][field][subfield] request = request_type(**request_init) # Mock the http request call within the method and fake a response. @@ -18587,14 +22692,14 @@ def test_stop_channel_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.stop_channel(request) + response = client.update_input(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_stop_channel_rest_interceptors(null_interceptor): +def test_update_input_rest_interceptors(null_interceptor): transport = transports.LivestreamServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -18610,16 +22715,16 @@ def test_stop_channel_rest_interceptors(null_interceptor): ) as transcode, mock.patch.object( operation.Operation, "_set_result_from_operation" ), mock.patch.object( - transports.LivestreamServiceRestInterceptor, "post_stop_channel" + transports.LivestreamServiceRestInterceptor, "post_update_input" ) as post, mock.patch.object( - transports.LivestreamServiceRestInterceptor, "post_stop_channel_with_metadata" + transports.LivestreamServiceRestInterceptor, "post_update_input_with_metadata" ) as post_with_metadata, mock.patch.object( - transports.LivestreamServiceRestInterceptor, "pre_stop_channel" + transports.LivestreamServiceRestInterceptor, "pre_update_input" ) as pre: pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = service.StopChannelRequest.pb(service.StopChannelRequest()) + pb_message = service.UpdateInputRequest.pb(service.UpdateInputRequest()) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -18633,7 +22738,7 @@ def test_stop_channel_rest_interceptors(null_interceptor): return_value = json_format.MessageToJson(operations_pb2.Operation()) req.return_value.content = return_value - request = service.StopChannelRequest() + request = service.UpdateInputRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), @@ -18642,7 +22747,7 @@ def test_stop_channel_rest_interceptors(null_interceptor): post.return_value = operations_pb2.Operation() post_with_metadata.return_value = operations_pb2.Operation(), metadata - client.stop_channel( + client.update_input( request, metadata=[ ("key", "val"), @@ -18655,12 +22760,12 @@ def test_stop_channel_rest_interceptors(null_interceptor): post_with_metadata.assert_called_once() -def test_create_input_rest_bad_request(request_type=service.CreateInputRequest): +def test_create_event_rest_bad_request(request_type=service.CreateEventRequest): client = LivestreamServiceClient( 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/channels/sample3"} request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -18675,71 +22780,44 @@ def test_create_input_rest_bad_request(request_type=service.CreateInputRequest): response_value.request = mock.Mock() req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.create_input(request) + client.create_event(request) @pytest.mark.parametrize( "request_type", [ - service.CreateInputRequest, + service.CreateEventRequest, dict, ], ) -def test_create_input_rest_call_success(request_type): +def test_create_event_rest_call_success(request_type): client = LivestreamServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/locations/sample2"} - request_init["input"] = { + request_init = {"parent": "projects/sample1/locations/sample2/channels/sample3"} + request_init["event"] = { "name": "name_value", "create_time": {"seconds": 751, "nanos": 543}, "update_time": {}, "labels": {}, - "type_": 1, - "tier": 1, - "uri": "uri_value", - "preprocessing_config": { - "audio": {"lufs": 0.442}, - "crop": { - "top_pixels": 1095, - "bottom_pixels": 1417, - "left_pixels": 1183, - "right_pixels": 1298, - }, - "pad": { - "top_pixels": 1095, - "bottom_pixels": 1417, - "left_pixels": 1183, - "right_pixels": 1298, - }, - }, - "security_rules": {"ip_ranges": ["ip_ranges_value1", "ip_ranges_value2"]}, - "input_stream_property": { - "last_establish_time": {}, - "video_streams": [ - { - "index": 536, - "video_format": { - "codec": "codec_value", - "width_pixels": 1300, - "height_pixels": 1389, - "frame_rate": 0.1046, - }, - } - ], - "audio_streams": [ + "input_switch": {"input_key": "input_key_value"}, + "ad_break": {"duration": {"seconds": 751, "nanos": 543}}, + "return_to_program": {}, + "slate": {"duration": {}, "asset": "asset_value"}, + "mute": {"duration": {}}, + "unmute": {}, + "execute_now": True, + "execution_time": {}, + "state": 1, + "error": { + "code": 411, + "message": "message_value", + "details": [ { - "index": 536, - "audio_format": { - "codec": "codec_value", - "channel_count": 1377, - "channel_layout": [ - "channel_layout_value1", - "channel_layout_value2", - ], - }, + "type_url": "type.googleapis.com/google.protobuf.Duration", + "value": b"\x08\x0c\x10\xdb\x07", } ], }, @@ -18749,7 +22827,7 @@ def test_create_input_rest_call_success(request_type): # See https://github.com/googleapis/gapic-generator-python/issues/1748 # Determine if the message type is proto-plus or protobuf - test_field = service.CreateInputRequest.meta.fields["input"] + test_field = service.CreateEventRequest.meta.fields["event"] def get_message_fields(field): # Given a field which is a message (composite type), return a list with @@ -18777,7 +22855,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["input"].items(): # pragma: NO COVER + for field, value in request_init["event"].items(): # pragma: NO COVER result = None is_repeated = False # For repeated fields @@ -18807,32 +22885,42 @@ def get_message_fields(field): subfield = subfield_to_delete.get("subfield") if subfield: if field_repeated: - for i in range(0, len(request_init["input"][field])): - del request_init["input"][field][i][subfield] + for i in range(0, len(request_init["event"][field])): + del request_init["event"][field][i][subfield] else: - del request_init["input"][field][subfield] + del request_init["event"][field][subfield] request = request_type(**request_init) # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name="operations/spam") + return_value = resources.Event( + name="name_value", + execute_now=True, + state=resources.Event.State.SCHEDULED, + ) # Wrap the value into a proper Response obj response_value = mock.Mock() response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = resources.Event.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value.content = json_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_input(request) + response = client.create_event(request) # Establish that the response is the type that we expect. - json_return_value = json_format.MessageToJson(return_value) + assert isinstance(response, resources.Event) + assert response.name == "name_value" + assert response.execute_now is True + assert response.state == resources.Event.State.SCHEDULED @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_create_input_rest_interceptors(null_interceptor): +def test_create_event_rest_interceptors(null_interceptor): transport = transports.LivestreamServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -18846,18 +22934,16 @@ def test_create_input_rest_interceptors(null_interceptor): ) as req, mock.patch.object( path_template, "transcode" ) as transcode, mock.patch.object( - operation.Operation, "_set_result_from_operation" - ), mock.patch.object( - transports.LivestreamServiceRestInterceptor, "post_create_input" + transports.LivestreamServiceRestInterceptor, "post_create_event" ) as post, mock.patch.object( - transports.LivestreamServiceRestInterceptor, "post_create_input_with_metadata" + transports.LivestreamServiceRestInterceptor, "post_create_event_with_metadata" ) as post_with_metadata, mock.patch.object( - transports.LivestreamServiceRestInterceptor, "pre_create_input" + transports.LivestreamServiceRestInterceptor, "pre_create_event" ) as pre: pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = service.CreateInputRequest.pb(service.CreateInputRequest()) + pb_message = service.CreateEventRequest.pb(service.CreateEventRequest()) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -18868,19 +22954,19 @@ def test_create_input_rest_interceptors(null_interceptor): req.return_value = mock.Mock() req.return_value.status_code = 200 req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - return_value = json_format.MessageToJson(operations_pb2.Operation()) + return_value = resources.Event.to_json(resources.Event()) req.return_value.content = return_value - request = service.CreateInputRequest() + request = service.CreateEventRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - post_with_metadata.return_value = operations_pb2.Operation(), metadata + post.return_value = resources.Event() + post_with_metadata.return_value = resources.Event(), metadata - client.create_input( + client.create_event( request, metadata=[ ("key", "val"), @@ -18893,12 +22979,12 @@ def test_create_input_rest_interceptors(null_interceptor): post_with_metadata.assert_called_once() -def test_list_inputs_rest_bad_request(request_type=service.ListInputsRequest): +def test_list_events_rest_bad_request(request_type=service.ListEventsRequest): client = LivestreamServiceClient( 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/channels/sample3"} request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -18913,29 +22999,29 @@ def test_list_inputs_rest_bad_request(request_type=service.ListInputsRequest): response_value.request = mock.Mock() req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.list_inputs(request) + client.list_events(request) @pytest.mark.parametrize( "request_type", [ - service.ListInputsRequest, + service.ListEventsRequest, dict, ], ) -def test_list_inputs_rest_call_success(request_type): +def test_list_events_rest_call_success(request_type): client = LivestreamServiceClient( 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/channels/sample3"} request = request_type(**request_init) # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = service.ListInputsResponse( + return_value = service.ListEventsResponse( next_page_token="next_page_token_value", unreachable=["unreachable_value"], ) @@ -18945,21 +23031,21 @@ def test_list_inputs_rest_call_success(request_type): response_value.status_code = 200 # Convert return value to protobuf type - return_value = service.ListInputsResponse.pb(return_value) + return_value = service.ListEventsResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value.content = json_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_inputs(request) + response = client.list_events(request) # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListInputsPager) + assert isinstance(response, pagers.ListEventsPager) assert response.next_page_token == "next_page_token_value" assert response.unreachable == ["unreachable_value"] @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_inputs_rest_interceptors(null_interceptor): +def test_list_events_rest_interceptors(null_interceptor): transport = transports.LivestreamServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -18973,16 +23059,16 @@ def test_list_inputs_rest_interceptors(null_interceptor): ) as req, mock.patch.object( path_template, "transcode" ) as transcode, mock.patch.object( - transports.LivestreamServiceRestInterceptor, "post_list_inputs" + transports.LivestreamServiceRestInterceptor, "post_list_events" ) as post, mock.patch.object( - transports.LivestreamServiceRestInterceptor, "post_list_inputs_with_metadata" + transports.LivestreamServiceRestInterceptor, "post_list_events_with_metadata" ) as post_with_metadata, mock.patch.object( - transports.LivestreamServiceRestInterceptor, "pre_list_inputs" + transports.LivestreamServiceRestInterceptor, "pre_list_events" ) as pre: pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = service.ListInputsRequest.pb(service.ListInputsRequest()) + pb_message = service.ListEventsRequest.pb(service.ListEventsRequest()) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -18993,19 +23079,19 @@ def test_list_inputs_rest_interceptors(null_interceptor): req.return_value = mock.Mock() req.return_value.status_code = 200 req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - return_value = service.ListInputsResponse.to_json(service.ListInputsResponse()) + return_value = service.ListEventsResponse.to_json(service.ListEventsResponse()) req.return_value.content = return_value - request = service.ListInputsRequest() + request = service.ListEventsRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = service.ListInputsResponse() - post_with_metadata.return_value = service.ListInputsResponse(), metadata + post.return_value = service.ListEventsResponse() + post_with_metadata.return_value = service.ListEventsResponse(), metadata - client.list_inputs( + client.list_events( request, metadata=[ ("key", "val"), @@ -19018,12 +23104,14 @@ def test_list_inputs_rest_interceptors(null_interceptor): post_with_metadata.assert_called_once() -def test_get_input_rest_bad_request(request_type=service.GetInputRequest): +def test_get_event_rest_bad_request(request_type=service.GetEventRequest): client = LivestreamServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/locations/sample2/inputs/sample3"} + request_init = { + "name": "projects/sample1/locations/sample2/channels/sample3/events/sample4" + } request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -19038,57 +23126,178 @@ def test_get_input_rest_bad_request(request_type=service.GetInputRequest): response_value.request = mock.Mock() req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.get_input(request) + client.get_event(request) @pytest.mark.parametrize( "request_type", [ - service.GetInputRequest, + service.GetEventRequest, dict, ], ) -def test_get_input_rest_call_success(request_type): +def test_get_event_rest_call_success(request_type): client = LivestreamServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/locations/sample2/inputs/sample3"} + request_init = { + "name": "projects/sample1/locations/sample2/channels/sample3/events/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 = resources.Input( + return_value = resources.Event( name="name_value", - type_=resources.Input.Type.RTMP_PUSH, - tier=resources.Input.Tier.SD, - uri="uri_value", + execute_now=True, + state=resources.Event.State.SCHEDULED, + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = resources.Event.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_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_event(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.Event) + assert response.name == "name_value" + assert response.execute_now is True + assert response.state == resources.Event.State.SCHEDULED + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_event_rest_interceptors(null_interceptor): + transport = transports.LivestreamServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.LivestreamServiceRestInterceptor(), + ) + client = LivestreamServiceClient(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.LivestreamServiceRestInterceptor, "post_get_event" + ) as post, mock.patch.object( + transports.LivestreamServiceRestInterceptor, "post_get_event_with_metadata" + ) as post_with_metadata, mock.patch.object( + transports.LivestreamServiceRestInterceptor, "pre_get_event" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = service.GetEventRequest.pb(service.GetEventRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = resources.Event.to_json(resources.Event()) + req.return_value.content = return_value + + request = service.GetEventRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = resources.Event() + post_with_metadata.return_value = resources.Event(), metadata + + client.get_event( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], ) + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_delete_event_rest_bad_request(request_type=service.DeleteEventRequest): + client = LivestreamServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/channels/sample3/events/sample4" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.delete_event(request) + + +@pytest.mark.parametrize( + "request_type", + [ + service.DeleteEventRequest, + dict, + ], +) +def test_delete_event_rest_call_success(request_type): + client = LivestreamServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/channels/sample3/events/sample4" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = None + # Wrap the value into a proper Response obj response_value = mock.Mock() response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = resources.Input.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_input(request) + response = client.delete_event(request) # Establish that the response is the type that we expect. - assert isinstance(response, resources.Input) - assert response.name == "name_value" - assert response.type_ == resources.Input.Type.RTMP_PUSH - assert response.tier == resources.Input.Tier.SD - assert response.uri == "uri_value" + assert response is None @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_input_rest_interceptors(null_interceptor): +def test_delete_event_rest_interceptors(null_interceptor): transport = transports.LivestreamServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -19102,16 +23311,10 @@ def test_get_input_rest_interceptors(null_interceptor): ) as req, mock.patch.object( path_template, "transcode" ) as transcode, mock.patch.object( - transports.LivestreamServiceRestInterceptor, "post_get_input" - ) as post, mock.patch.object( - transports.LivestreamServiceRestInterceptor, "post_get_input_with_metadata" - ) as post_with_metadata, mock.patch.object( - transports.LivestreamServiceRestInterceptor, "pre_get_input" + transports.LivestreamServiceRestInterceptor, "pre_delete_event" ) as pre: pre.assert_not_called() - post.assert_not_called() - post_with_metadata.assert_not_called() - pb_message = service.GetInputRequest.pb(service.GetInputRequest()) + pb_message = service.DeleteEventRequest.pb(service.DeleteEventRequest()) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -19122,19 +23325,15 @@ def test_get_input_rest_interceptors(null_interceptor): req.return_value = mock.Mock() req.return_value.status_code = 200 req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - return_value = resources.Input.to_json(resources.Input()) - req.return_value.content = return_value - request = service.GetInputRequest() + request = service.DeleteEventRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = resources.Input() - post_with_metadata.return_value = resources.Input(), metadata - client.get_input( + client.delete_event( request, metadata=[ ("key", "val"), @@ -19143,16 +23342,14 @@ def test_get_input_rest_interceptors(null_interceptor): ) pre.assert_called_once() - post.assert_called_once() - post_with_metadata.assert_called_once() -def test_delete_input_rest_bad_request(request_type=service.DeleteInputRequest): +def test_list_clips_rest_bad_request(request_type=service.ListClipsRequest): client = LivestreamServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/locations/sample2/inputs/sample3"} + request_init = {"parent": "projects/sample1/locations/sample2/channels/sample3"} request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -19167,45 +23364,53 @@ def test_delete_input_rest_bad_request(request_type=service.DeleteInputRequest): response_value.request = mock.Mock() req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.delete_input(request) + client.list_clips(request) @pytest.mark.parametrize( "request_type", [ - service.DeleteInputRequest, + service.ListClipsRequest, dict, ], ) -def test_delete_input_rest_call_success(request_type): +def test_list_clips_rest_call_success(request_type): client = LivestreamServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/locations/sample2/inputs/sample3"} + request_init = {"parent": "projects/sample1/locations/sample2/channels/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 = service.ListClipsResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], + ) # Wrap the value into a proper Response obj response_value = mock.Mock() response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = service.ListClipsResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value.content = json_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_input(request) + response = client.list_clips(request) # Establish that the response is the type that we expect. - json_return_value = json_format.MessageToJson(return_value) + assert isinstance(response, pagers.ListClipsPager) + assert response.next_page_token == "next_page_token_value" + assert response.unreachable == ["unreachable_value"] @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_delete_input_rest_interceptors(null_interceptor): +def test_list_clips_rest_interceptors(null_interceptor): transport = transports.LivestreamServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -19219,18 +23424,16 @@ def test_delete_input_rest_interceptors(null_interceptor): ) as req, mock.patch.object( path_template, "transcode" ) as transcode, mock.patch.object( - operation.Operation, "_set_result_from_operation" - ), mock.patch.object( - transports.LivestreamServiceRestInterceptor, "post_delete_input" + transports.LivestreamServiceRestInterceptor, "post_list_clips" ) as post, mock.patch.object( - transports.LivestreamServiceRestInterceptor, "post_delete_input_with_metadata" + transports.LivestreamServiceRestInterceptor, "post_list_clips_with_metadata" ) as post_with_metadata, mock.patch.object( - transports.LivestreamServiceRestInterceptor, "pre_delete_input" + transports.LivestreamServiceRestInterceptor, "pre_list_clips" ) as pre: pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = service.DeleteInputRequest.pb(service.DeleteInputRequest()) + pb_message = service.ListClipsRequest.pb(service.ListClipsRequest()) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -19241,19 +23444,19 @@ def test_delete_input_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 = service.ListClipsResponse.to_json(service.ListClipsResponse()) req.return_value.content = return_value - request = service.DeleteInputRequest() + request = service.ListClipsRequest() 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 = service.ListClipsResponse() + post_with_metadata.return_value = service.ListClipsResponse(), metadata - client.delete_input( + client.list_clips( request, metadata=[ ("key", "val"), @@ -19266,13 +23469,13 @@ def test_delete_input_rest_interceptors(null_interceptor): post_with_metadata.assert_called_once() -def test_update_input_rest_bad_request(request_type=service.UpdateInputRequest): +def test_get_clip_rest_bad_request(request_type=service.GetClipRequest): client = LivestreamServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding request_init = { - "input": {"name": "projects/sample1/locations/sample2/inputs/sample3"} + "name": "projects/sample1/locations/sample2/channels/sample3/clips/sample4" } request = request_type(**request_init) @@ -19288,166 +23491,59 @@ def test_update_input_rest_bad_request(request_type=service.UpdateInputRequest): response_value.request = mock.Mock() req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.update_input(request) + client.get_clip(request) @pytest.mark.parametrize( "request_type", [ - service.UpdateInputRequest, + service.GetClipRequest, dict, ], ) -def test_update_input_rest_call_success(request_type): +def test_get_clip_rest_call_success(request_type): client = LivestreamServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding request_init = { - "input": {"name": "projects/sample1/locations/sample2/inputs/sample3"} - } - request_init["input"] = { - "name": "projects/sample1/locations/sample2/inputs/sample3", - "create_time": {"seconds": 751, "nanos": 543}, - "update_time": {}, - "labels": {}, - "type_": 1, - "tier": 1, - "uri": "uri_value", - "preprocessing_config": { - "audio": {"lufs": 0.442}, - "crop": { - "top_pixels": 1095, - "bottom_pixels": 1417, - "left_pixels": 1183, - "right_pixels": 1298, - }, - "pad": { - "top_pixels": 1095, - "bottom_pixels": 1417, - "left_pixels": 1183, - "right_pixels": 1298, - }, - }, - "security_rules": {"ip_ranges": ["ip_ranges_value1", "ip_ranges_value2"]}, - "input_stream_property": { - "last_establish_time": {}, - "video_streams": [ - { - "index": 536, - "video_format": { - "codec": "codec_value", - "width_pixels": 1300, - "height_pixels": 1389, - "frame_rate": 0.1046, - }, - } - ], - "audio_streams": [ - { - "index": 536, - "audio_format": { - "codec": "codec_value", - "channel_count": 1377, - "channel_layout": [ - "channel_layout_value1", - "channel_layout_value2", - ], - }, - } - ], - }, + "name": "projects/sample1/locations/sample2/channels/sample3/clips/sample4" } - # The version of a generated dependency at test runtime may differ from the version used during generation. - # Delete any fields which are not present in the current runtime dependency - # See https://github.com/googleapis/gapic-generator-python/issues/1748 - - # Determine if the message type is proto-plus or protobuf - test_field = service.UpdateInputRequest.meta.fields["input"] - - 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["input"].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["input"][field])): - del request_init["input"][field][i][subfield] - else: - del request_init["input"][field][subfield] request = request_type(**request_init) # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name="operations/spam") + return_value = resources.Clip( + name="name_value", + state=resources.Clip.State.PENDING, + output_uri="output_uri_value", + output_type=resources.Clip.OutputType.MANIFEST, + ) # Wrap the value into a proper Response obj response_value = mock.Mock() response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = resources.Clip.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value.content = json_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_input(request) + response = client.get_clip(request) # Establish that the response is the type that we expect. - json_return_value = json_format.MessageToJson(return_value) + assert isinstance(response, resources.Clip) + assert response.name == "name_value" + assert response.state == resources.Clip.State.PENDING + assert response.output_uri == "output_uri_value" + assert response.output_type == resources.Clip.OutputType.MANIFEST @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_update_input_rest_interceptors(null_interceptor): +def test_get_clip_rest_interceptors(null_interceptor): transport = transports.LivestreamServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -19461,18 +23557,16 @@ def test_update_input_rest_interceptors(null_interceptor): ) as req, mock.patch.object( path_template, "transcode" ) as transcode, mock.patch.object( - operation.Operation, "_set_result_from_operation" - ), mock.patch.object( - transports.LivestreamServiceRestInterceptor, "post_update_input" + transports.LivestreamServiceRestInterceptor, "post_get_clip" ) as post, mock.patch.object( - transports.LivestreamServiceRestInterceptor, "post_update_input_with_metadata" + transports.LivestreamServiceRestInterceptor, "post_get_clip_with_metadata" ) as post_with_metadata, mock.patch.object( - transports.LivestreamServiceRestInterceptor, "pre_update_input" + transports.LivestreamServiceRestInterceptor, "pre_get_clip" ) as pre: pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = service.UpdateInputRequest.pb(service.UpdateInputRequest()) + pb_message = service.GetClipRequest.pb(service.GetClipRequest()) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -19483,19 +23577,19 @@ def test_update_input_rest_interceptors(null_interceptor): req.return_value = mock.Mock() req.return_value.status_code = 200 req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - return_value = json_format.MessageToJson(operations_pb2.Operation()) + return_value = resources.Clip.to_json(resources.Clip()) req.return_value.content = return_value - request = service.UpdateInputRequest() + request = service.GetClipRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - post_with_metadata.return_value = operations_pb2.Operation(), metadata + post.return_value = resources.Clip() + post_with_metadata.return_value = resources.Clip(), metadata - client.update_input( + client.get_clip( request, metadata=[ ("key", "val"), @@ -19508,7 +23602,7 @@ def test_update_input_rest_interceptors(null_interceptor): post_with_metadata.assert_called_once() -def test_create_event_rest_bad_request(request_type=service.CreateEventRequest): +def test_create_clip_rest_bad_request(request_type=service.CreateClipRequest): client = LivestreamServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) @@ -19528,37 +23622,31 @@ def test_create_event_rest_bad_request(request_type=service.CreateEventRequest): response_value.request = mock.Mock() req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.create_event(request) + client.create_clip(request) @pytest.mark.parametrize( "request_type", [ - service.CreateEventRequest, + service.CreateClipRequest, dict, ], ) -def test_create_event_rest_call_success(request_type): +def test_create_clip_rest_call_success(request_type): client = LivestreamServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding request_init = {"parent": "projects/sample1/locations/sample2/channels/sample3"} - request_init["event"] = { + request_init["clip"] = { "name": "name_value", "create_time": {"seconds": 751, "nanos": 543}, + "start_time": {}, "update_time": {}, "labels": {}, - "input_switch": {"input_key": "input_key_value"}, - "ad_break": {"duration": {"seconds": 751, "nanos": 543}}, - "return_to_program": {}, - "slate": {"duration": {}, "asset": "asset_value"}, - "mute": {"duration": {}}, - "unmute": {}, - "execute_now": True, - "execution_time": {}, "state": 1, + "output_uri": "output_uri_value", "error": { "code": 411, "message": "message_value", @@ -19569,13 +23657,18 @@ def test_create_event_rest_call_success(request_type): } ], }, + "slices": [{"time_slice": {"markin_time": {}, "markout_time": {}}}], + "clip_manifests": [ + {"manifest_key": "manifest_key_value", "output_uri": "output_uri_value"} + ], + "output_type": 1, } # The version of a generated dependency at test runtime may differ from the version used during generation. # Delete any fields which are not present in the current runtime dependency # See https://github.com/googleapis/gapic-generator-python/issues/1748 # Determine if the message type is proto-plus or protobuf - test_field = service.CreateEventRequest.meta.fields["event"] + test_field = service.CreateClipRequest.meta.fields["clip"] def get_message_fields(field): # Given a field which is a message (composite type), return a list with @@ -19603,7 +23696,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["event"].items(): # pragma: NO COVER + for field, value in request_init["clip"].items(): # pragma: NO COVER result = None is_repeated = False # For repeated fields @@ -19633,167 +23726,32 @@ def get_message_fields(field): subfield = subfield_to_delete.get("subfield") if subfield: if field_repeated: - for i in range(0, len(request_init["event"][field])): - del request_init["event"][field][i][subfield] + for i in range(0, len(request_init["clip"][field])): + del request_init["clip"][field][i][subfield] else: - del request_init["event"][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 = resources.Event( - name="name_value", - execute_now=True, - state=resources.Event.State.SCHEDULED, - ) - - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = resources.Event.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_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_event(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, resources.Event) - assert response.name == "name_value" - assert response.execute_now is True - assert response.state == resources.Event.State.SCHEDULED - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_create_event_rest_interceptors(null_interceptor): - transport = transports.LivestreamServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.LivestreamServiceRestInterceptor(), - ) - client = LivestreamServiceClient(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.LivestreamServiceRestInterceptor, "post_create_event" - ) as post, mock.patch.object( - transports.LivestreamServiceRestInterceptor, "post_create_event_with_metadata" - ) as post_with_metadata, mock.patch.object( - transports.LivestreamServiceRestInterceptor, "pre_create_event" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - post_with_metadata.assert_not_called() - pb_message = service.CreateEventRequest.pb(service.CreateEventRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = mock.Mock() - req.return_value.status_code = 200 - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - return_value = resources.Event.to_json(resources.Event()) - req.return_value.content = return_value - - request = service.CreateEventRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = resources.Event() - post_with_metadata.return_value = resources.Event(), metadata - - client.create_event( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - post_with_metadata.assert_called_once() - - -def test_list_events_rest_bad_request(request_type=service.ListEventsRequest): - client = LivestreamServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/locations/sample2/channels/sample3"} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, "request") as req, pytest.raises( - core_exceptions.BadRequest - ): - # Wrap the value into a proper Response obj - response_value = mock.Mock() - json_return_value = "" - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = mock.Mock() - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.list_events(request) - - -@pytest.mark.parametrize( - "request_type", - [ - service.ListEventsRequest, - dict, - ], -) -def test_list_events_rest_call_success(request_type): - client = LivestreamServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/locations/sample2/channels/sample3"} + del request_init["clip"][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 = service.ListEventsResponse( - 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 = service.ListEventsResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value.content = json_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_events(request) + response = client.create_clip(request) # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListEventsPager) - 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_events_rest_interceptors(null_interceptor): +def test_create_clip_rest_interceptors(null_interceptor): transport = transports.LivestreamServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -19807,16 +23765,18 @@ def test_list_events_rest_interceptors(null_interceptor): ) as req, mock.patch.object( path_template, "transcode" ) as transcode, mock.patch.object( - transports.LivestreamServiceRestInterceptor, "post_list_events" + operation.Operation, "_set_result_from_operation" + ), mock.patch.object( + transports.LivestreamServiceRestInterceptor, "post_create_clip" ) as post, mock.patch.object( - transports.LivestreamServiceRestInterceptor, "post_list_events_with_metadata" + transports.LivestreamServiceRestInterceptor, "post_create_clip_with_metadata" ) as post_with_metadata, mock.patch.object( - transports.LivestreamServiceRestInterceptor, "pre_list_events" + transports.LivestreamServiceRestInterceptor, "pre_create_clip" ) as pre: pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = service.ListEventsRequest.pb(service.ListEventsRequest()) + pb_message = service.CreateClipRequest.pb(service.CreateClipRequest()) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -19827,19 +23787,19 @@ def test_list_events_rest_interceptors(null_interceptor): req.return_value = mock.Mock() req.return_value.status_code = 200 req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - return_value = service.ListEventsResponse.to_json(service.ListEventsResponse()) + return_value = json_format.MessageToJson(operations_pb2.Operation()) req.return_value.content = return_value - request = service.ListEventsRequest() + request = service.CreateClipRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = service.ListEventsResponse() - post_with_metadata.return_value = service.ListEventsResponse(), metadata + post.return_value = operations_pb2.Operation() + post_with_metadata.return_value = operations_pb2.Operation(), metadata - client.list_events( + client.create_clip( request, metadata=[ ("key", "val"), @@ -19852,13 +23812,13 @@ def test_list_events_rest_interceptors(null_interceptor): post_with_metadata.assert_called_once() -def test_get_event_rest_bad_request(request_type=service.GetEventRequest): +def test_delete_clip_rest_bad_request(request_type=service.DeleteClipRequest): client = LivestreamServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding request_init = { - "name": "projects/sample1/locations/sample2/channels/sample3/events/sample4" + "name": "projects/sample1/locations/sample2/channels/sample3/clips/sample4" } request = request_type(**request_init) @@ -19874,57 +23834,47 @@ def test_get_event_rest_bad_request(request_type=service.GetEventRequest): response_value.request = mock.Mock() req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.get_event(request) + client.delete_clip(request) @pytest.mark.parametrize( "request_type", [ - service.GetEventRequest, + service.DeleteClipRequest, dict, ], ) -def test_get_event_rest_call_success(request_type): +def test_delete_clip_rest_call_success(request_type): client = LivestreamServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding request_init = { - "name": "projects/sample1/locations/sample2/channels/sample3/events/sample4" + "name": "projects/sample1/locations/sample2/channels/sample3/clips/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 = resources.Event( - name="name_value", - execute_now=True, - state=resources.Event.State.SCHEDULED, - ) + 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 = resources.Event.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value.content = json_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_event(request) + response = client.delete_clip(request) # Establish that the response is the type that we expect. - assert isinstance(response, resources.Event) - assert response.name == "name_value" - assert response.execute_now is True - assert response.state == resources.Event.State.SCHEDULED + json_return_value = json_format.MessageToJson(return_value) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_event_rest_interceptors(null_interceptor): +def test_delete_clip_rest_interceptors(null_interceptor): transport = transports.LivestreamServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -19938,16 +23888,18 @@ def test_get_event_rest_interceptors(null_interceptor): ) as req, mock.patch.object( path_template, "transcode" ) as transcode, mock.patch.object( - transports.LivestreamServiceRestInterceptor, "post_get_event" + operation.Operation, "_set_result_from_operation" + ), mock.patch.object( + transports.LivestreamServiceRestInterceptor, "post_delete_clip" ) as post, mock.patch.object( - transports.LivestreamServiceRestInterceptor, "post_get_event_with_metadata" + transports.LivestreamServiceRestInterceptor, "post_delete_clip_with_metadata" ) as post_with_metadata, mock.patch.object( - transports.LivestreamServiceRestInterceptor, "pre_get_event" + transports.LivestreamServiceRestInterceptor, "pre_delete_clip" ) as pre: pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = service.GetEventRequest.pb(service.GetEventRequest()) + pb_message = service.DeleteClipRequest.pb(service.DeleteClipRequest()) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -19958,19 +23910,19 @@ def test_get_event_rest_interceptors(null_interceptor): req.return_value = mock.Mock() req.return_value.status_code = 200 req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - return_value = resources.Event.to_json(resources.Event()) + return_value = json_format.MessageToJson(operations_pb2.Operation()) req.return_value.content = return_value - request = service.GetEventRequest() + request = service.DeleteClipRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = resources.Event() - post_with_metadata.return_value = resources.Event(), metadata + post.return_value = operations_pb2.Operation() + post_with_metadata.return_value = operations_pb2.Operation(), metadata - client.get_event( + client.delete_clip( request, metadata=[ ("key", "val"), @@ -19983,14 +23935,14 @@ def test_get_event_rest_interceptors(null_interceptor): post_with_metadata.assert_called_once() -def test_delete_event_rest_bad_request(request_type=service.DeleteEventRequest): +def test_create_dvr_session_rest_bad_request( + request_type=service.CreateDvrSessionRequest, +): client = LivestreamServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = { - "name": "projects/sample1/locations/sample2/channels/sample3/events/sample4" - } + request_init = {"parent": "projects/sample1/locations/sample2/channels/sample3"} request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -20005,47 +23957,133 @@ def test_delete_event_rest_bad_request(request_type=service.DeleteEventRequest): response_value.request = mock.Mock() req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.delete_event(request) + client.create_dvr_session(request) @pytest.mark.parametrize( "request_type", [ - service.DeleteEventRequest, + service.CreateDvrSessionRequest, dict, ], ) -def test_delete_event_rest_call_success(request_type): +def test_create_dvr_session_rest_call_success(request_type): client = LivestreamServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = { - "name": "projects/sample1/locations/sample2/channels/sample3/events/sample4" + request_init = {"parent": "projects/sample1/locations/sample2/channels/sample3"} + request_init["dvr_session"] = { + "name": "name_value", + "create_time": {"seconds": 751, "nanos": 543}, + "update_time": {}, + "labels": {}, + "state": 1, + "error": { + "code": 411, + "message": "message_value", + "details": [ + { + "type_url": "type.googleapis.com/google.protobuf.Duration", + "value": b"\x08\x0c\x10\xdb\x07", + } + ], + }, + "dvr_manifests": [ + {"manifest_key": "manifest_key_value", "output_uri": "output_uri_value"} + ], + "dvr_windows": [{"time_interval": {"start_time": {}, "end_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 = service.CreateDvrSessionRequest.meta.fields["dvr_session"] + + 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["dvr_session"].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["dvr_session"][field])): + del request_init["dvr_session"][field][i][subfield] + else: + del request_init["dvr_session"][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 = 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_return_value = json_format.MessageToJson(return_value) response_value.content = json_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_event(request) + response = client.create_dvr_session(request) # Establish that the response is the type that we expect. - assert response is None + json_return_value = json_format.MessageToJson(return_value) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_delete_event_rest_interceptors(null_interceptor): +def test_create_dvr_session_rest_interceptors(null_interceptor): transport = transports.LivestreamServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -20059,10 +24097,21 @@ def test_delete_event_rest_interceptors(null_interceptor): ) as req, mock.patch.object( path_template, "transcode" ) as transcode, mock.patch.object( - transports.LivestreamServiceRestInterceptor, "pre_delete_event" + operation.Operation, "_set_result_from_operation" + ), mock.patch.object( + transports.LivestreamServiceRestInterceptor, "post_create_dvr_session" + ) as post, mock.patch.object( + transports.LivestreamServiceRestInterceptor, + "post_create_dvr_session_with_metadata", + ) as post_with_metadata, mock.patch.object( + transports.LivestreamServiceRestInterceptor, "pre_create_dvr_session" ) as pre: pre.assert_not_called() - pb_message = service.DeleteEventRequest.pb(service.DeleteEventRequest()) + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = service.CreateDvrSessionRequest.pb( + service.CreateDvrSessionRequest() + ) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -20073,15 +24122,19 @@ def test_delete_event_rest_interceptors(null_interceptor): req.return_value = mock.Mock() req.return_value.status_code = 200 req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value - request = service.DeleteEventRequest() + request = service.CreateDvrSessionRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + post_with_metadata.return_value = operations_pb2.Operation(), metadata - client.delete_event( + client.create_dvr_session( request, metadata=[ ("key", "val"), @@ -20090,9 +24143,13 @@ def test_delete_event_rest_interceptors(null_interceptor): ) pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() -def test_list_clips_rest_bad_request(request_type=service.ListClipsRequest): +def test_list_dvr_sessions_rest_bad_request( + request_type=service.ListDvrSessionsRequest, +): client = LivestreamServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) @@ -20112,17 +24169,17 @@ def test_list_clips_rest_bad_request(request_type=service.ListClipsRequest): response_value.request = mock.Mock() req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.list_clips(request) + client.list_dvr_sessions(request) @pytest.mark.parametrize( "request_type", [ - service.ListClipsRequest, + service.ListDvrSessionsRequest, dict, ], ) -def test_list_clips_rest_call_success(request_type): +def test_list_dvr_sessions_rest_call_success(request_type): client = LivestreamServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) @@ -20134,7 +24191,7 @@ def test_list_clips_rest_call_success(request_type): # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = service.ListClipsResponse( + return_value = service.ListDvrSessionsResponse( next_page_token="next_page_token_value", unreachable=["unreachable_value"], ) @@ -20144,21 +24201,21 @@ def test_list_clips_rest_call_success(request_type): response_value.status_code = 200 # Convert return value to protobuf type - return_value = service.ListClipsResponse.pb(return_value) + return_value = service.ListDvrSessionsResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value.content = json_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_clips(request) + response = client.list_dvr_sessions(request) # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListClipsPager) + assert isinstance(response, pagers.ListDvrSessionsPager) assert response.next_page_token == "next_page_token_value" assert response.unreachable == ["unreachable_value"] @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_clips_rest_interceptors(null_interceptor): +def test_list_dvr_sessions_rest_interceptors(null_interceptor): transport = transports.LivestreamServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -20172,16 +24229,17 @@ def test_list_clips_rest_interceptors(null_interceptor): ) as req, mock.patch.object( path_template, "transcode" ) as transcode, mock.patch.object( - transports.LivestreamServiceRestInterceptor, "post_list_clips" + transports.LivestreamServiceRestInterceptor, "post_list_dvr_sessions" ) as post, mock.patch.object( - transports.LivestreamServiceRestInterceptor, "post_list_clips_with_metadata" + transports.LivestreamServiceRestInterceptor, + "post_list_dvr_sessions_with_metadata", ) as post_with_metadata, mock.patch.object( - transports.LivestreamServiceRestInterceptor, "pre_list_clips" + transports.LivestreamServiceRestInterceptor, "pre_list_dvr_sessions" ) as pre: pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = service.ListClipsRequest.pb(service.ListClipsRequest()) + pb_message = service.ListDvrSessionsRequest.pb(service.ListDvrSessionsRequest()) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -20192,19 +24250,21 @@ def test_list_clips_rest_interceptors(null_interceptor): req.return_value = mock.Mock() req.return_value.status_code = 200 req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - return_value = service.ListClipsResponse.to_json(service.ListClipsResponse()) + return_value = service.ListDvrSessionsResponse.to_json( + service.ListDvrSessionsResponse() + ) req.return_value.content = return_value - request = service.ListClipsRequest() + request = service.ListDvrSessionsRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = service.ListClipsResponse() - post_with_metadata.return_value = service.ListClipsResponse(), metadata + post.return_value = service.ListDvrSessionsResponse() + post_with_metadata.return_value = service.ListDvrSessionsResponse(), metadata - client.list_clips( + client.list_dvr_sessions( request, metadata=[ ("key", "val"), @@ -20217,13 +24277,13 @@ def test_list_clips_rest_interceptors(null_interceptor): post_with_metadata.assert_called_once() -def test_get_clip_rest_bad_request(request_type=service.GetClipRequest): +def test_get_dvr_session_rest_bad_request(request_type=service.GetDvrSessionRequest): client = LivestreamServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding request_init = { - "name": "projects/sample1/locations/sample2/channels/sample3/clips/sample4" + "name": "projects/sample1/locations/sample2/channels/sample3/dvrSessions/sample4" } request = request_type(**request_init) @@ -20239,34 +24299,33 @@ def test_get_clip_rest_bad_request(request_type=service.GetClipRequest): response_value.request = mock.Mock() req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.get_clip(request) + client.get_dvr_session(request) @pytest.mark.parametrize( "request_type", [ - service.GetClipRequest, + service.GetDvrSessionRequest, dict, ], ) -def test_get_clip_rest_call_success(request_type): +def test_get_dvr_session_rest_call_success(request_type): client = LivestreamServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding request_init = { - "name": "projects/sample1/locations/sample2/channels/sample3/clips/sample4" + "name": "projects/sample1/locations/sample2/channels/sample3/dvrSessions/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 = resources.Clip( + return_value = resources.DvrSession( name="name_value", - state=resources.Clip.State.PENDING, - output_uri="output_uri_value", + state=resources.DvrSession.State.PENDING, ) # Wrap the value into a proper Response obj @@ -20274,22 +24333,21 @@ def test_get_clip_rest_call_success(request_type): response_value.status_code = 200 # Convert return value to protobuf type - return_value = resources.Clip.pb(return_value) + return_value = resources.DvrSession.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value.content = json_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_clip(request) + response = client.get_dvr_session(request) # Establish that the response is the type that we expect. - assert isinstance(response, resources.Clip) + assert isinstance(response, resources.DvrSession) assert response.name == "name_value" - assert response.state == resources.Clip.State.PENDING - assert response.output_uri == "output_uri_value" + assert response.state == resources.DvrSession.State.PENDING @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_clip_rest_interceptors(null_interceptor): +def test_get_dvr_session_rest_interceptors(null_interceptor): transport = transports.LivestreamServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -20303,16 +24361,17 @@ def test_get_clip_rest_interceptors(null_interceptor): ) as req, mock.patch.object( path_template, "transcode" ) as transcode, mock.patch.object( - transports.LivestreamServiceRestInterceptor, "post_get_clip" + transports.LivestreamServiceRestInterceptor, "post_get_dvr_session" ) as post, mock.patch.object( - transports.LivestreamServiceRestInterceptor, "post_get_clip_with_metadata" + transports.LivestreamServiceRestInterceptor, + "post_get_dvr_session_with_metadata", ) as post_with_metadata, mock.patch.object( - transports.LivestreamServiceRestInterceptor, "pre_get_clip" + transports.LivestreamServiceRestInterceptor, "pre_get_dvr_session" ) as pre: pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = service.GetClipRequest.pb(service.GetClipRequest()) + pb_message = service.GetDvrSessionRequest.pb(service.GetDvrSessionRequest()) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -20323,19 +24382,19 @@ def test_get_clip_rest_interceptors(null_interceptor): req.return_value = mock.Mock() req.return_value.status_code = 200 req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - return_value = resources.Clip.to_json(resources.Clip()) + return_value = resources.DvrSession.to_json(resources.DvrSession()) req.return_value.content = return_value - request = service.GetClipRequest() + request = service.GetDvrSessionRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = resources.Clip() - post_with_metadata.return_value = resources.Clip(), metadata + post.return_value = resources.DvrSession() + post_with_metadata.return_value = resources.DvrSession(), metadata - client.get_clip( + client.get_dvr_session( request, metadata=[ ("key", "val"), @@ -20348,12 +24407,16 @@ def test_get_clip_rest_interceptors(null_interceptor): post_with_metadata.assert_called_once() -def test_create_clip_rest_bad_request(request_type=service.CreateClipRequest): +def test_delete_dvr_session_rest_bad_request( + request_type=service.DeleteDvrSessionRequest, +): client = LivestreamServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/locations/sample2/channels/sample3"} + request_init = { + "name": "projects/sample1/locations/sample2/channels/sample3/dvrSessions/sample4" + } request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -20368,113 +24431,25 @@ def test_create_clip_rest_bad_request(request_type=service.CreateClipRequest): response_value.request = mock.Mock() req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.create_clip(request) + client.delete_dvr_session(request) @pytest.mark.parametrize( "request_type", [ - service.CreateClipRequest, + service.DeleteDvrSessionRequest, dict, ], ) -def test_create_clip_rest_call_success(request_type): +def test_delete_dvr_session_rest_call_success(request_type): client = LivestreamServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/locations/sample2/channels/sample3"} - request_init["clip"] = { - "name": "name_value", - "create_time": {"seconds": 751, "nanos": 543}, - "start_time": {}, - "update_time": {}, - "labels": {}, - "state": 1, - "output_uri": "output_uri_value", - "error": { - "code": 411, - "message": "message_value", - "details": [ - { - "type_url": "type.googleapis.com/google.protobuf.Duration", - "value": b"\x08\x0c\x10\xdb\x07", - } - ], - }, - "slices": [{"time_slice": {"markin_time": {}, "markout_time": {}}}], - "clip_manifests": [ - {"manifest_key": "manifest_key_value", "output_uri": "output_uri_value"} - ], - } - # The version of a generated dependency at test runtime may differ from the version used during generation. - # Delete any fields which are not present in the current runtime dependency - # See https://github.com/googleapis/gapic-generator-python/issues/1748 - - # Determine if the message type is proto-plus or protobuf - test_field = service.CreateClipRequest.meta.fields["clip"] - - 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["clip"].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["clip"][field])): - del request_init["clip"][field][i][subfield] - else: - del request_init["clip"][field][subfield] + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/channels/sample3/dvrSessions/sample4" + } request = request_type(**request_init) # Mock the http request call within the method and fake a response. @@ -20489,14 +24464,14 @@ def get_message_fields(field): response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.create_clip(request) + response = client.delete_dvr_session(request) # Establish that the response is the type that we expect. json_return_value = json_format.MessageToJson(return_value) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_create_clip_rest_interceptors(null_interceptor): +def test_delete_dvr_session_rest_interceptors(null_interceptor): transport = transports.LivestreamServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -20512,16 +24487,19 @@ def test_create_clip_rest_interceptors(null_interceptor): ) as transcode, mock.patch.object( operation.Operation, "_set_result_from_operation" ), mock.patch.object( - transports.LivestreamServiceRestInterceptor, "post_create_clip" + transports.LivestreamServiceRestInterceptor, "post_delete_dvr_session" ) as post, mock.patch.object( - transports.LivestreamServiceRestInterceptor, "post_create_clip_with_metadata" + transports.LivestreamServiceRestInterceptor, + "post_delete_dvr_session_with_metadata", ) as post_with_metadata, mock.patch.object( - transports.LivestreamServiceRestInterceptor, "pre_create_clip" + transports.LivestreamServiceRestInterceptor, "pre_delete_dvr_session" ) as pre: pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = service.CreateClipRequest.pb(service.CreateClipRequest()) + pb_message = service.DeleteDvrSessionRequest.pb( + service.DeleteDvrSessionRequest() + ) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -20535,7 +24513,7 @@ def test_create_clip_rest_interceptors(null_interceptor): return_value = json_format.MessageToJson(operations_pb2.Operation()) req.return_value.content = return_value - request = service.CreateClipRequest() + request = service.DeleteDvrSessionRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), @@ -20544,7 +24522,7 @@ def test_create_clip_rest_interceptors(null_interceptor): post.return_value = operations_pb2.Operation() post_with_metadata.return_value = operations_pb2.Operation(), metadata - client.create_clip( + client.delete_dvr_session( request, metadata=[ ("key", "val"), @@ -20557,13 +24535,17 @@ def test_create_clip_rest_interceptors(null_interceptor): post_with_metadata.assert_called_once() -def test_delete_clip_rest_bad_request(request_type=service.DeleteClipRequest): +def test_update_dvr_session_rest_bad_request( + request_type=service.UpdateDvrSessionRequest, +): client = LivestreamServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding request_init = { - "name": "projects/sample1/locations/sample2/channels/sample3/clips/sample4" + "dvr_session": { + "name": "projects/sample1/locations/sample2/channels/sample3/dvrSessions/sample4" + } } request = request_type(**request_init) @@ -20579,25 +24561,115 @@ def test_delete_clip_rest_bad_request(request_type=service.DeleteClipRequest): response_value.request = mock.Mock() req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.delete_clip(request) + client.update_dvr_session(request) @pytest.mark.parametrize( "request_type", [ - service.DeleteClipRequest, + service.UpdateDvrSessionRequest, dict, ], ) -def test_delete_clip_rest_call_success(request_type): +def test_update_dvr_session_rest_call_success(request_type): client = LivestreamServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding request_init = { - "name": "projects/sample1/locations/sample2/channels/sample3/clips/sample4" + "dvr_session": { + "name": "projects/sample1/locations/sample2/channels/sample3/dvrSessions/sample4" + } + } + request_init["dvr_session"] = { + "name": "projects/sample1/locations/sample2/channels/sample3/dvrSessions/sample4", + "create_time": {"seconds": 751, "nanos": 543}, + "update_time": {}, + "labels": {}, + "state": 1, + "error": { + "code": 411, + "message": "message_value", + "details": [ + { + "type_url": "type.googleapis.com/google.protobuf.Duration", + "value": b"\x08\x0c\x10\xdb\x07", + } + ], + }, + "dvr_manifests": [ + {"manifest_key": "manifest_key_value", "output_uri": "output_uri_value"} + ], + "dvr_windows": [{"time_interval": {"start_time": {}, "end_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 = service.UpdateDvrSessionRequest.meta.fields["dvr_session"] + + 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["dvr_session"].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["dvr_session"][field])): + del request_init["dvr_session"][field][i][subfield] + else: + del request_init["dvr_session"][field][subfield] request = request_type(**request_init) # Mock the http request call within the method and fake a response. @@ -20612,14 +24684,14 @@ def test_delete_clip_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_clip(request) + response = client.update_dvr_session(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_clip_rest_interceptors(null_interceptor): +def test_update_dvr_session_rest_interceptors(null_interceptor): transport = transports.LivestreamServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -20635,16 +24707,19 @@ def test_delete_clip_rest_interceptors(null_interceptor): ) as transcode, mock.patch.object( operation.Operation, "_set_result_from_operation" ), mock.patch.object( - transports.LivestreamServiceRestInterceptor, "post_delete_clip" + transports.LivestreamServiceRestInterceptor, "post_update_dvr_session" ) as post, mock.patch.object( - transports.LivestreamServiceRestInterceptor, "post_delete_clip_with_metadata" + transports.LivestreamServiceRestInterceptor, + "post_update_dvr_session_with_metadata", ) as post_with_metadata, mock.patch.object( - transports.LivestreamServiceRestInterceptor, "pre_delete_clip" + transports.LivestreamServiceRestInterceptor, "pre_update_dvr_session" ) as pre: pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = service.DeleteClipRequest.pb(service.DeleteClipRequest()) + pb_message = service.UpdateDvrSessionRequest.pb( + service.UpdateDvrSessionRequest() + ) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -20658,7 +24733,7 @@ def test_delete_clip_rest_interceptors(null_interceptor): return_value = json_format.MessageToJson(operations_pb2.Operation()) req.return_value.content = return_value - request = service.DeleteClipRequest() + request = service.UpdateDvrSessionRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), @@ -20667,7 +24742,7 @@ def test_delete_clip_rest_interceptors(null_interceptor): post.return_value = operations_pb2.Operation() post_with_metadata.return_value = operations_pb2.Operation(), metadata - client.delete_clip( + client.update_dvr_session( request, metadata=[ ("key", "val"), @@ -22352,6 +26427,114 @@ def test_delete_clip_empty_call_rest(): assert args[0] == request_msg +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_create_dvr_session_empty_call_rest(): + client = LivestreamServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_dvr_session), "__call__" + ) as call: + client.create_dvr_session(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.CreateDvrSessionRequest() + + assert args[0] == request_msg + + +# This 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_dvr_sessions_empty_call_rest(): + client = LivestreamServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_dvr_sessions), "__call__" + ) as call: + client.list_dvr_sessions(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.ListDvrSessionsRequest() + + assert args[0] == request_msg + + +# This 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_dvr_session_empty_call_rest(): + client = LivestreamServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_dvr_session), "__call__") as call: + client.get_dvr_session(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.GetDvrSessionRequest() + + assert args[0] == request_msg + + +# This 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_dvr_session_empty_call_rest(): + client = LivestreamServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_dvr_session), "__call__" + ) as call: + client.delete_dvr_session(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.DeleteDvrSessionRequest() + + assert args[0] == request_msg + + +# This 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_dvr_session_empty_call_rest(): + client = LivestreamServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_dvr_session), "__call__" + ) as call: + client.update_dvr_session(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.UpdateDvrSessionRequest() + + assert args[0] == request_msg + + # This 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_asset_empty_call_rest(): @@ -22542,6 +26725,11 @@ def test_livestream_service_base_transport(): "get_clip", "create_clip", "delete_clip", + "create_dvr_session", + "list_dvr_sessions", + "get_dvr_session", + "delete_dvr_session", + "update_dvr_session", "create_asset", "delete_asset", "get_asset", @@ -22877,6 +27065,21 @@ def test_livestream_service_client_transport_session_collision(transport_name): session1 = client1.transport.delete_clip._session session2 = client2.transport.delete_clip._session assert session1 != session2 + session1 = client1.transport.create_dvr_session._session + session2 = client2.transport.create_dvr_session._session + assert session1 != session2 + session1 = client1.transport.list_dvr_sessions._session + session2 = client2.transport.list_dvr_sessions._session + assert session1 != session2 + session1 = client1.transport.get_dvr_session._session + session2 = client2.transport.get_dvr_session._session + assert session1 != session2 + session1 = client1.transport.delete_dvr_session._session + session2 = client2.transport.delete_dvr_session._session + assert session1 != session2 + session1 = client1.transport.update_dvr_session._session + session2 = client2.transport.update_dvr_session._session + assert session1 != session2 session1 = client1.transport.create_asset._session session2 = client2.transport.create_asset._session assert session1 != session2 @@ -23138,11 +27341,42 @@ def test_parse_clip_path(): assert expected == actual -def test_event_path(): +def test_dvr_session_path(): project = "winkle" location = "nautilus" channel = "scallop" - event = "abalone" + dvr_session = "abalone" + expected = "projects/{project}/locations/{location}/channels/{channel}/dvrSessions/{dvr_session}".format( + project=project, + location=location, + channel=channel, + dvr_session=dvr_session, + ) + actual = LivestreamServiceClient.dvr_session_path( + project, location, channel, dvr_session + ) + assert expected == actual + + +def test_parse_dvr_session_path(): + expected = { + "project": "squid", + "location": "clam", + "channel": "whelk", + "dvr_session": "octopus", + } + path = LivestreamServiceClient.dvr_session_path(**expected) + + # Check that the path construction is reversible. + actual = LivestreamServiceClient.parse_dvr_session_path(path) + assert expected == actual + + +def test_event_path(): + project = "oyster" + location = "nudibranch" + channel = "cuttlefish" + event = "mussel" expected = "projects/{project}/locations/{location}/channels/{channel}/events/{event}".format( project=project, location=location, @@ -23155,10 +27389,10 @@ def test_event_path(): def test_parse_event_path(): expected = { - "project": "squid", - "location": "clam", - "channel": "whelk", - "event": "octopus", + "project": "winkle", + "location": "nautilus", + "channel": "scallop", + "event": "abalone", } path = LivestreamServiceClient.event_path(**expected) @@ -23168,9 +27402,9 @@ def test_parse_event_path(): def test_input_path(): - project = "oyster" - location = "nudibranch" - input = "cuttlefish" + project = "squid" + location = "clam" + input = "whelk" expected = "projects/{project}/locations/{location}/inputs/{input}".format( project=project, location=location, @@ -23182,9 +27416,9 @@ def test_input_path(): def test_parse_input_path(): expected = { - "project": "mussel", - "location": "winkle", - "input": "nautilus", + "project": "octopus", + "location": "oyster", + "input": "nudibranch", } path = LivestreamServiceClient.input_path(**expected) @@ -23194,8 +27428,8 @@ def test_parse_input_path(): def test_network_path(): - project = "scallop" - network = "abalone" + project = "cuttlefish" + network = "mussel" expected = "projects/{project}/global/networks/{network}".format( project=project, network=network, @@ -23206,8 +27440,8 @@ def test_network_path(): def test_parse_network_path(): expected = { - "project": "squid", - "network": "clam", + "project": "winkle", + "network": "nautilus", } path = LivestreamServiceClient.network_path(**expected) @@ -23217,9 +27451,9 @@ def test_parse_network_path(): def test_pool_path(): - project = "whelk" - location = "octopus" - pool = "oyster" + project = "scallop" + location = "abalone" + pool = "squid" expected = "projects/{project}/locations/{location}/pools/{pool}".format( project=project, location=location, @@ -23231,9 +27465,9 @@ def test_pool_path(): def test_parse_pool_path(): expected = { - "project": "nudibranch", - "location": "cuttlefish", - "pool": "mussel", + "project": "clam", + "location": "whelk", + "pool": "octopus", } path = LivestreamServiceClient.pool_path(**expected) @@ -23243,9 +27477,9 @@ def test_parse_pool_path(): def test_secret_version_path(): - project = "winkle" - secret = "nautilus" - version = "scallop" + project = "oyster" + secret = "nudibranch" + version = "cuttlefish" expected = "projects/{project}/secrets/{secret}/versions/{version}".format( project=project, secret=secret, @@ -23257,9 +27491,9 @@ def test_secret_version_path(): def test_parse_secret_version_path(): expected = { - "project": "abalone", - "secret": "squid", - "version": "clam", + "project": "mussel", + "secret": "winkle", + "version": "nautilus", } path = LivestreamServiceClient.secret_version_path(**expected) @@ -23269,7 +27503,7 @@ def test_parse_secret_version_path(): def test_common_billing_account_path(): - billing_account = "whelk" + billing_account = "scallop" expected = "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -23279,7 +27513,7 @@ def test_common_billing_account_path(): def test_parse_common_billing_account_path(): expected = { - "billing_account": "octopus", + "billing_account": "abalone", } path = LivestreamServiceClient.common_billing_account_path(**expected) @@ -23289,7 +27523,7 @@ def test_parse_common_billing_account_path(): def test_common_folder_path(): - folder = "oyster" + folder = "squid" expected = "folders/{folder}".format( folder=folder, ) @@ -23299,7 +27533,7 @@ def test_common_folder_path(): def test_parse_common_folder_path(): expected = { - "folder": "nudibranch", + "folder": "clam", } path = LivestreamServiceClient.common_folder_path(**expected) @@ -23309,7 +27543,7 @@ def test_parse_common_folder_path(): def test_common_organization_path(): - organization = "cuttlefish" + organization = "whelk" expected = "organizations/{organization}".format( organization=organization, ) @@ -23319,7 +27553,7 @@ def test_common_organization_path(): def test_parse_common_organization_path(): expected = { - "organization": "mussel", + "organization": "octopus", } path = LivestreamServiceClient.common_organization_path(**expected) @@ -23329,7 +27563,7 @@ def test_parse_common_organization_path(): def test_common_project_path(): - project = "winkle" + project = "oyster" expected = "projects/{project}".format( project=project, ) @@ -23339,7 +27573,7 @@ def test_common_project_path(): def test_parse_common_project_path(): expected = { - "project": "nautilus", + "project": "nudibranch", } path = LivestreamServiceClient.common_project_path(**expected) @@ -23349,8 +27583,8 @@ def test_parse_common_project_path(): def test_common_location_path(): - project = "scallop" - location = "abalone" + project = "cuttlefish" + location = "mussel" expected = "projects/{project}/locations/{location}".format( project=project, location=location, @@ -23361,8 +27595,8 @@ def test_common_location_path(): def test_parse_common_location_path(): expected = { - "project": "squid", - "location": "clam", + "project": "winkle", + "location": "nautilus", } path = LivestreamServiceClient.common_location_path(**expected)