diff --git a/.librarian/state.yaml b/.librarian/state.yaml index f290283e8cb8..ae7761016257 100644 --- a/.librarian/state.yaml +++ b/.librarian/state.yaml @@ -2,7 +2,7 @@ image: us-central1-docker.pkg.dev/cloud-sdk-librarian-prod/images-prod/python-li libraries: - id: google-cloud-dlp version: 3.32.0 - last_generated_commit: f8776fec04e336527ba7279d960105533a1c4e21 + last_generated_commit: a32846d78b106d72f51e5e2186bc3be9dbf45c7d apis: - path: google/privacy/dlp/v2 service_config: dlp_v2.yaml @@ -23,9 +23,10 @@ libraries: tag_format: '{id}-v{version}' - id: google-cloud-eventarc version: 1.15.3 - last_generated_commit: d300b151a973ce0425ae4ad07b3de957ca31bec6 + last_generated_commit: a32846d78b106d72f51e5e2186bc3be9dbf45c7d apis: - path: google/cloud/eventarc/v1 + service_config: eventarc_v1.yaml source_roots: - packages/google-cloud-eventarc preserve_regex: @@ -43,9 +44,10 @@ libraries: tag_format: '{id}-v{version}' - id: google-cloud-video-live-stream version: 1.12.0 - last_generated_commit: d300b151a973ce0425ae4ad07b3de957ca31bec6 + last_generated_commit: a32846d78b106d72f51e5e2186bc3be9dbf45c7d apis: - path: google/cloud/video/livestream/v1 + service_config: livestream_v1.yaml source_roots: - packages/google-cloud-video-live-stream preserve_regex: @@ -63,9 +65,10 @@ libraries: tag_format: '{id}-v{version}' - id: google-ads-marketingplatform-admin version: 0.1.6 - last_generated_commit: d300b151a973ce0425ae4ad07b3de957ca31bec6 + last_generated_commit: a32846d78b106d72f51e5e2186bc3be9dbf45c7d apis: - path: google/marketingplatform/admin/v1alpha + service_config: marketingplatformadmin_v1alpha.yaml source_roots: - packages/google-ads-marketingplatform-admin preserve_regex: @@ -83,13 +86,18 @@ libraries: tag_format: '{id}-v{version}' - id: google-ai-generativelanguage version: 0.7.0 - last_generated_commit: d300b151a973ce0425ae4ad07b3de957ca31bec6 + last_generated_commit: a32846d78b106d72f51e5e2186bc3be9dbf45c7d apis: - path: google/ai/generativelanguage/v1 + service_config: generativelanguage_v1.yaml - path: google/ai/generativelanguage/v1beta + service_config: generativelanguage_v1beta.yaml - path: google/ai/generativelanguage/v1beta3 + service_config: generativelanguage_v1beta3.yaml - path: google/ai/generativelanguage/v1beta2 + service_config: generativelanguage_v1beta2.yaml - path: google/ai/generativelanguage/v1alpha + service_config: generativelanguage_v1alpha.yaml source_roots: - packages/google-ai-generativelanguage preserve_regex: @@ -107,10 +115,12 @@ libraries: tag_format: '{id}-v{version}' - id: google-analytics-admin version: 0.25.0 - last_generated_commit: d300b151a973ce0425ae4ad07b3de957ca31bec6 + last_generated_commit: a32846d78b106d72f51e5e2186bc3be9dbf45c7d apis: - path: google/analytics/admin/v1beta + service_config: analyticsadmin_v1beta.yaml - path: google/analytics/admin/v1alpha + service_config: analyticsadmin_v1alpha.yaml source_roots: - packages/google-analytics-admin preserve_regex: @@ -128,10 +138,12 @@ libraries: tag_format: '{id}-v{version}' - id: google-analytics-data version: 0.18.19 - last_generated_commit: d300b151a973ce0425ae4ad07b3de957ca31bec6 + last_generated_commit: a32846d78b106d72f51e5e2186bc3be9dbf45c7d apis: - path: google/analytics/data/v1alpha + service_config: analyticsdata_v1alpha.yaml - path: google/analytics/data/v1beta + service_config: analyticsdata_v1beta.yaml source_roots: - packages/google-analytics-data preserve_regex: @@ -149,9 +161,10 @@ libraries: tag_format: '{id}-v{version}' - id: google-ads-admanager version: 0.3.0 - last_generated_commit: d300b151a973ce0425ae4ad07b3de957ca31bec6 + last_generated_commit: a32846d78b106d72f51e5e2186bc3be9dbf45c7d apis: - path: google/ads/admanager/v1 + service_config: admanager_v1.yaml source_roots: - packages/google-ads-admanager preserve_regex: diff --git a/packages/google-ads-admanager/.OwlBot.yaml b/packages/google-ads-admanager/.OwlBot.yaml deleted file mode 100644 index 8ffa8f8c99b4..000000000000 --- a/packages/google-ads-admanager/.OwlBot.yaml +++ /dev/null @@ -1,18 +0,0 @@ -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -deep-copy-regex: - - source: /google/ads/admanager/(v.*)/.*-py - dest: /owl-bot-staging/google-ads-admanager/$1 -api-name: google-ads-admanager diff --git a/packages/google-ads-marketingplatform-admin/.OwlBot.yaml b/packages/google-ads-marketingplatform-admin/.OwlBot.yaml deleted file mode 100644 index d397bf3a63bd..000000000000 --- a/packages/google-ads-marketingplatform-admin/.OwlBot.yaml +++ /dev/null @@ -1,18 +0,0 @@ -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -deep-copy-regex: - - source: /google/marketingplatform/admin/(v.*)/.*-py - dest: /owl-bot-staging/google-ads-marketingplatform-admin/$1 -api-name: google-ads-marketingplatform-admin diff --git a/packages/google-ai-generativelanguage/.OwlBot.yaml b/packages/google-ai-generativelanguage/.OwlBot.yaml deleted file mode 100644 index 183cc83a8c98..000000000000 --- a/packages/google-ai-generativelanguage/.OwlBot.yaml +++ /dev/null @@ -1,18 +0,0 @@ -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -deep-copy-regex: - - source: /google/ai/generativelanguage/(.*)/.*-py - dest: /owl-bot-staging/google-ai-generativelanguage/$1 -api-name: google-ai-generativelanguage diff --git a/packages/google-analytics-admin/.OwlBot.yaml b/packages/google-analytics-admin/.OwlBot.yaml deleted file mode 100644 index 1de0fb5f3948..000000000000 --- a/packages/google-analytics-admin/.OwlBot.yaml +++ /dev/null @@ -1,25 +0,0 @@ -# Copyright 2021 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - - -deep-remove-regex: - - /owl-bot-staging - -deep-copy-regex: - - source: /google/analytics/admin/(v.*)/.*-py - dest: /owl-bot-staging/google-analytics-admin/$1 - -begin-after-commit-hash: ee56c3493ec6aeb237ff515ecea949710944a20f - -api-name: google-analytics-admin diff --git a/packages/google-analytics-data/.OwlBot.yaml b/packages/google-analytics-data/.OwlBot.yaml deleted file mode 100644 index 10c0584a8a17..000000000000 --- a/packages/google-analytics-data/.OwlBot.yaml +++ /dev/null @@ -1,25 +0,0 @@ -# Copyright 2021 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - - -deep-remove-regex: - - /owl-bot-staging - -deep-copy-regex: - - source: /google/analytics/data/(v.*)/.*-py - dest: /owl-bot-staging/google-analytics-data/$1 - -begin-after-commit-hash: a21f1091413a260393548c1b2ac44b7347923f08 - -api-name: google-analytics-data diff --git a/packages/google-cloud-dlp/samples/generated_samples/snippet_metadata_google.privacy.dlp.v2.json b/packages/google-cloud-dlp/samples/generated_samples/snippet_metadata_google.privacy.dlp.v2.json index 1a04cc109785..8e523fad2045 100644 --- a/packages/google-cloud-dlp/samples/generated_samples/snippet_metadata_google.privacy.dlp.v2.json +++ b/packages/google-cloud-dlp/samples/generated_samples/snippet_metadata_google.privacy.dlp.v2.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-dlp", - "version": "3.32.0" + "version": "0.1.0" }, "snippets": [ { diff --git a/packages/google-cloud-eventarc/.OwlBot.yaml b/packages/google-cloud-eventarc/.OwlBot.yaml deleted file mode 100644 index 324cb015a2ca..000000000000 --- a/packages/google-cloud-eventarc/.OwlBot.yaml +++ /dev/null @@ -1,24 +0,0 @@ -# Copyright 2021 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - - -deep-remove-regex: - - /owl-bot-staging - -deep-copy-regex: - - source: /google/cloud/eventarc/(v.*)/.*-py - dest: /owl-bot-staging/google-cloud-eventarc/$1 - -begin-after-commit-hash: 70f7f0525414fe4dfeb2fc2e81546b073f83a621 -api-name: google-cloud-eventarc diff --git a/packages/google-cloud-eventarc/google/cloud/eventarc_v1/services/eventarc/async_client.py b/packages/google-cloud-eventarc/google/cloud/eventarc_v1/services/eventarc/async_client.py index 8a2784ec40e7..9f7208d448b1 100644 --- a/packages/google-cloud-eventarc/google/cloud/eventarc_v1/services/eventarc/async_client.py +++ b/packages/google-cloud-eventarc/google/cloud/eventarc_v1/services/eventarc/async_client.py @@ -2459,7 +2459,9 @@ async def get_google_channel_config( timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> google_channel_config.GoogleChannelConfig: - r"""Get a GoogleChannelConfig + r"""Get a GoogleChannelConfig. + The name of the GoogleChannelConfig in the response is + ALWAYS coded with projectID. .. code-block:: python @@ -2864,7 +2866,7 @@ async def sample_list_message_buses(): ListMessageBuses method. parent (:class:`str`): Required. The parent collection to - list triggers on. + list message buses on. This corresponds to the ``parent`` field on the ``request`` instance; if ``request`` is provided, this @@ -3137,7 +3139,7 @@ async def sample_create_message_bus(): message_bus_id (:class:`str`): Required. The user-provided ID to be assigned to the MessageBus. It should match the format - (^\ `a-z <[a-z0-9-]{0,61}[a-z0-9]>`__?$) + ``^[a-z]([a-z0-9-]{0,61}[a-z0-9])?$``. This corresponds to the ``message_bus_id`` field on the ``request`` instance; if ``request`` is provided, this @@ -3813,7 +3815,7 @@ async def sample_create_enrollment(): enrollment_id (:class:`str`): Required. The user-provided ID to be assigned to the Enrollment. It should match the format - (^\ `a-z <[a-z0-9-]{0,61}[a-z0-9]>`__?$). + ``^[a-z]([a-z0-9-]{0,61}[a-z0-9])?$``. This corresponds to the ``enrollment_id`` field on the ``request`` instance; if ``request`` is provided, this @@ -4485,8 +4487,9 @@ async def sample_create_pipeline(): on the ``request`` instance; if ``request`` is provided, this should not be set. pipeline_id (:class:`str`): - Required. The user-provided ID to be - assigned to the Pipeline. + Required. The user-provided ID to be assigned to the + Pipeline. It should match the format + ``^[a-z]([a-z0-9-]{0,61}[a-z0-9])?$``. This corresponds to the ``pipeline_id`` field on the ``request`` instance; if ``request`` is provided, this @@ -5156,7 +5159,7 @@ async def sample_create_google_api_source(): google_api_source_id (:class:`str`): Required. The user-provided ID to be assigned to the GoogleApiSource. It should match the format - (^\ `a-z <[a-z0-9-]{0,61}[a-z0-9]>`__?$). + ``^[a-z]([a-z0-9-]{0,61}[a-z0-9])?$``. This corresponds to the ``google_api_source_id`` field on the ``request`` instance; if ``request`` is provided, this diff --git a/packages/google-cloud-eventarc/google/cloud/eventarc_v1/services/eventarc/client.py b/packages/google-cloud-eventarc/google/cloud/eventarc_v1/services/eventarc/client.py index f38396bc2313..b1e787007700 100644 --- a/packages/google-cloud-eventarc/google/cloud/eventarc_v1/services/eventarc/client.py +++ b/packages/google-cloud-eventarc/google/cloud/eventarc_v1/services/eventarc/client.py @@ -3119,7 +3119,9 @@ def get_google_channel_config( timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> google_channel_config.GoogleChannelConfig: - r"""Get a GoogleChannelConfig + r"""Get a GoogleChannelConfig. + The name of the GoogleChannelConfig in the response is + ALWAYS coded with projectID. .. code-block:: python @@ -3519,7 +3521,7 @@ def sample_list_message_buses(): ListMessageBuses method. parent (str): Required. The parent collection to - list triggers on. + list message buses on. This corresponds to the ``parent`` field on the ``request`` instance; if ``request`` is provided, this @@ -3788,7 +3790,7 @@ def sample_create_message_bus(): message_bus_id (str): Required. The user-provided ID to be assigned to the MessageBus. It should match the format - (^\ `a-z <[a-z0-9-]{0,61}[a-z0-9]>`__?$) + ``^[a-z]([a-z0-9-]{0,61}[a-z0-9])?$``. This corresponds to the ``message_bus_id`` field on the ``request`` instance; if ``request`` is provided, this @@ -4449,7 +4451,7 @@ def sample_create_enrollment(): enrollment_id (str): Required. The user-provided ID to be assigned to the Enrollment. It should match the format - (^\ `a-z <[a-z0-9-]{0,61}[a-z0-9]>`__?$). + ``^[a-z]([a-z0-9-]{0,61}[a-z0-9])?$``. This corresponds to the ``enrollment_id`` field on the ``request`` instance; if ``request`` is provided, this @@ -5106,8 +5108,9 @@ def sample_create_pipeline(): on the ``request`` instance; if ``request`` is provided, this should not be set. pipeline_id (str): - Required. The user-provided ID to be - assigned to the Pipeline. + Required. The user-provided ID to be assigned to the + Pipeline. It should match the format + ``^[a-z]([a-z0-9-]{0,61}[a-z0-9])?$``. This corresponds to the ``pipeline_id`` field on the ``request`` instance; if ``request`` is provided, this @@ -5762,7 +5765,7 @@ def sample_create_google_api_source(): google_api_source_id (str): Required. The user-provided ID to be assigned to the GoogleApiSource. It should match the format - (^\ `a-z <[a-z0-9-]{0,61}[a-z0-9]>`__?$). + ``^[a-z]([a-z0-9-]{0,61}[a-z0-9])?$``. This corresponds to the ``google_api_source_id`` field on the ``request`` instance; if ``request`` is provided, this diff --git a/packages/google-cloud-eventarc/google/cloud/eventarc_v1/services/eventarc/transports/grpc.py b/packages/google-cloud-eventarc/google/cloud/eventarc_v1/services/eventarc/transports/grpc.py index f98c8c89b98f..2b0f2cbf7c21 100644 --- a/packages/google-cloud-eventarc/google/cloud/eventarc_v1/services/eventarc/transports/grpc.py +++ b/packages/google-cloud-eventarc/google/cloud/eventarc_v1/services/eventarc/transports/grpc.py @@ -783,7 +783,9 @@ def get_google_channel_config( ]: r"""Return a callable for the get google channel config method over gRPC. - Get a GoogleChannelConfig + Get a GoogleChannelConfig. + The name of the GoogleChannelConfig in the response is + ALWAYS coded with projectID. Returns: Callable[[~.GetGoogleChannelConfigRequest], diff --git a/packages/google-cloud-eventarc/google/cloud/eventarc_v1/services/eventarc/transports/grpc_asyncio.py b/packages/google-cloud-eventarc/google/cloud/eventarc_v1/services/eventarc/transports/grpc_asyncio.py index bb6c7884c844..c5d027eb72e7 100644 --- a/packages/google-cloud-eventarc/google/cloud/eventarc_v1/services/eventarc/transports/grpc_asyncio.py +++ b/packages/google-cloud-eventarc/google/cloud/eventarc_v1/services/eventarc/transports/grpc_asyncio.py @@ -806,7 +806,9 @@ def get_google_channel_config( ]: r"""Return a callable for the get google channel config method over gRPC. - Get a GoogleChannelConfig + Get a GoogleChannelConfig. + The name of the GoogleChannelConfig in the response is + ALWAYS coded with projectID. Returns: Callable[[~.GetGoogleChannelConfigRequest], diff --git a/packages/google-cloud-eventarc/google/cloud/eventarc_v1/services/eventarc/transports/rest_base.py b/packages/google-cloud-eventarc/google/cloud/eventarc_v1/services/eventarc/transports/rest_base.py index ed1b51badd6a..63829611cb7b 100644 --- a/packages/google-cloud-eventarc/google/cloud/eventarc_v1/services/eventarc/transports/rest_base.py +++ b/packages/google-cloud-eventarc/google/cloud/eventarc_v1/services/eventarc/transports/rest_base.py @@ -2141,6 +2141,10 @@ def _get_http_options(): "method": "get", "uri": "/v1/{resource=projects/*/locations/*/pipelines/*}:getIamPolicy", }, + { + "method": "get", + "uri": "/v1/{resource=projects/*/locations/*/kafkaSources/*}:getIamPolicy", + }, { "method": "get", "uri": "/v1/{resource=projects/*/locations/*/googleApiSources/*}:getIamPolicy", @@ -2196,6 +2200,11 @@ def _get_http_options(): "uri": "/v1/{resource=projects/*/locations/*/pipelines/*}:setIamPolicy", "body": "*", }, + { + "method": "post", + "uri": "/v1/{resource=projects/*/locations/*/kafkaSources/*}:setIamPolicy", + "body": "*", + }, { "method": "post", "uri": "/v1/{resource=projects/*/locations/*/googleApiSources/*}:setIamPolicy", @@ -2257,6 +2266,11 @@ def _get_http_options(): "uri": "/v1/{resource=projects/*/locations/*/pipelines/*}:testIamPermissions", "body": "*", }, + { + "method": "post", + "uri": "/v1/{resource=projects/*/locations/*/kafkaSources/*}:testIamPermissions", + "body": "*", + }, { "method": "post", "uri": "/v1/{resource=projects/*/locations/*/googleApiSources/*}:testIamPermissions", diff --git a/packages/google-cloud-eventarc/google/cloud/eventarc_v1/types/channel.py b/packages/google-cloud-eventarc/google/cloud/eventarc_v1/types/channel.py index b5be07af1491..b4eed51d35d8 100644 --- a/packages/google-cloud-eventarc/google/cloud/eventarc_v1/types/channel.py +++ b/packages/google-cloud-eventarc/google/cloud/eventarc_v1/types/channel.py @@ -71,8 +71,8 @@ class Channel(proto.Message): channel. The token must be used by the provider to register the channel for publishing. crypto_key_name (str): - Resource name of a KMS crypto key (managed by the user) used - to encrypt/decrypt their event data. + Optional. Resource name of a KMS crypto key (managed by the + user) used to encrypt/decrypt their event data. It must match the pattern ``projects/*/locations/*/keyRings/*/cryptoKeys/*``. @@ -80,6 +80,8 @@ class Channel(proto.Message): Output only. Whether or not this Channel satisfies the requirements of physical zone separation + labels (MutableMapping[str, str]): + Optional. Resource labels. """ class State(proto.Enum): @@ -162,6 +164,11 @@ class State(proto.Enum): proto.BOOL, number=12, ) + labels: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=13, + ) __all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-cloud-eventarc/google/cloud/eventarc_v1/types/channel_connection.py b/packages/google-cloud-eventarc/google/cloud/eventarc_v1/types/channel_connection.py index c114d4ce609e..04d1f23a7dfe 100644 --- a/packages/google-cloud-eventarc/google/cloud/eventarc_v1/types/channel_connection.py +++ b/packages/google-cloud-eventarc/google/cloud/eventarc_v1/types/channel_connection.py @@ -57,6 +57,8 @@ class ChannelConnection(proto.Message): ChannelConnection to bind the channel with the provider project. This field will not be stored in the provider resource. + labels (MutableMapping[str, str]): + Optional. Resource labels. """ name: str = proto.Field( @@ -85,6 +87,11 @@ class ChannelConnection(proto.Message): proto.STRING, number=8, ) + labels: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=9, + ) __all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-cloud-eventarc/google/cloud/eventarc_v1/types/enrollment.py b/packages/google-cloud-eventarc/google/cloud/eventarc_v1/types/enrollment.py index f66235083b11..ae0757a71872 100644 --- a/packages/google-cloud-eventarc/google/cloud/eventarc_v1/types/enrollment.py +++ b/packages/google-cloud-eventarc/google/cloud/eventarc_v1/types/enrollment.py @@ -63,9 +63,9 @@ class Enrollment(proto.Message): Required. A CEL expression identifying which messages this enrollment applies to. message_bus (str): - Required. Resource name of the message bus - identifying the source of the messages. It - matches the form + Required. Immutable. Resource name of the + message bus identifying the source of the + messages. It matches the form projects/{project}/locations/{location}/messageBuses/{messageBus}. destination (str): Required. Destination is the Pipeline that the Enrollment is diff --git a/packages/google-cloud-eventarc/google/cloud/eventarc_v1/types/eventarc.py b/packages/google-cloud-eventarc/google/cloud/eventarc_v1/types/eventarc.py index 5271ad67a0a0..9a11d0c921a9 100644 --- a/packages/google-cloud-eventarc/google/cloud/eventarc_v1/types/eventarc.py +++ b/packages/google-cloud-eventarc/google/cloud/eventarc_v1/types/eventarc.py @@ -776,7 +776,7 @@ class ListMessageBusesRequest(proto.Message): Attributes: parent (str): Required. The parent collection to list - triggers on. + message buses on. page_size (int): Optional. The maximum number of results to return on each page. @@ -935,7 +935,7 @@ class CreateMessageBusRequest(proto.Message): message_bus_id (str): Required. The user-provided ID to be assigned to the MessageBus. It should match the format - (^\ `a-z <[a-z0-9-]{0,61}[a-z0-9]>`__?$) + ``^[a-z]([a-z0-9-]{0,61}[a-z0-9])?$``. validate_only (bool): Optional. If set, validate the request and preview the review, but do not post it. @@ -1150,7 +1150,7 @@ class CreateEnrollmentRequest(proto.Message): enrollment_id (str): Required. The user-provided ID to be assigned to the Enrollment. It should match the format - (^\ `a-z <[a-z0-9-]{0,61}[a-z0-9]>`__?$). + ``^[a-z]([a-z0-9-]{0,61}[a-z0-9])?$``. validate_only (bool): Optional. If set, validate the request and preview the review, but do not post it. @@ -1363,8 +1363,9 @@ class CreatePipelineRequest(proto.Message): pipeline (google.cloud.eventarc_v1.types.Pipeline): Required. The pipeline to create. pipeline_id (str): - Required. The user-provided ID to be assigned - to the Pipeline. + Required. The user-provided ID to be assigned to the + Pipeline. It should match the format + ``^[a-z]([a-z0-9-]{0,61}[a-z0-9])?$``. validate_only (bool): Optional. If set, validate the request and preview the review, but do not post it. @@ -1582,7 +1583,7 @@ class CreateGoogleApiSourceRequest(proto.Message): google_api_source_id (str): Required. The user-provided ID to be assigned to the GoogleApiSource. It should match the format - (^\ `a-z <[a-z0-9-]{0,61}[a-z0-9]>`__?$). + ``^[a-z]([a-z0-9-]{0,61}[a-z0-9])?$``. validate_only (bool): Optional. If set, validate the request and preview the review, but do not post it. diff --git a/packages/google-cloud-eventarc/google/cloud/eventarc_v1/types/google_channel_config.py b/packages/google-cloud-eventarc/google/cloud/eventarc_v1/types/google_channel_config.py index a0ab10108fab..3569fcde3c17 100644 --- a/packages/google-cloud-eventarc/google/cloud/eventarc_v1/types/google_channel_config.py +++ b/packages/google-cloud-eventarc/google/cloud/eventarc_v1/types/google_channel_config.py @@ -40,6 +40,9 @@ class GoogleChannelConfig(proto.Message): Required. The resource name of the config. Must be in the format of, ``projects/{project}/locations/{location}/googleChannelConfig``. + In API responses, the config name always includes the + projectID, regardless of whether the projectID or + projectNumber was provided. update_time (google.protobuf.timestamp_pb2.Timestamp): Output only. The last-modified time. crypto_key_name (str): @@ -48,6 +51,8 @@ class GoogleChannelConfig(proto.Message): It must match the pattern ``projects/*/locations/*/keyRings/*/cryptoKeys/*``. + labels (MutableMapping[str, str]): + Optional. Resource labels. """ name: str = proto.Field( @@ -63,6 +68,11 @@ class GoogleChannelConfig(proto.Message): proto.STRING, number=7, ) + labels: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=8, + ) __all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-cloud-eventarc/google/cloud/eventarc_v1/types/pipeline.py b/packages/google-cloud-eventarc/google/cloud/eventarc_v1/types/pipeline.py index d6a962960878..59adf87a83e2 100644 --- a/packages/google-cloud-eventarc/google/cloud/eventarc_v1/types/pipeline.py +++ b/packages/google-cloud-eventarc/google/cloud/eventarc_v1/types/pipeline.py @@ -106,6 +106,10 @@ class Pipeline(proto.Message): might be sent only on create requests to ensure that the client has an up-to-date value before proceeding. + satisfies_pzs (bool): + Output only. Whether or not this Pipeline + satisfies the requirements of physical zone + separation """ class MessagePayloadFormat(proto.Message): @@ -231,11 +235,11 @@ class Destination(proto.Message): Optional. An authentication config used to authenticate message requests, such that destinations can verify the source. For example, - this can be used with private GCP destinations - that require GCP credentials to access like - Cloud Run. This field is optional and should be - set only by users interested in authenticated - push + this can be used with private Google Cloud + destinations that require Google Cloud + credentials for access like Cloud Run. This + field is optional and should be set only by + users interested in authenticated push. output_payload_format (google.cloud.eventarc_v1.types.Pipeline.MessagePayloadFormat): Optional. The message format before it is delivered to the destination. If not set, the message will be delivered in @@ -265,7 +269,7 @@ class HttpEndpoint(proto.Message): Attributes: uri (str): - Required. The URI of the HTTP enpdoint. + Required. The URI of the HTTP endpoint. The value must be a RFC2396 URI string. Examples: ``https://svc.us-central1.p.local:8080/route``. Only the @@ -277,9 +281,11 @@ class HttpEndpoint(proto.Message): If a binding expression is not specified here, the message is treated as a CloudEvent and is mapped to the HTTP request according to the CloudEvent HTTP Protocol Binding Binary - Content Mode. In this representation, all fields except the - ``data`` and ``datacontenttype`` field on the message are - mapped to HTTP request headers with a prefix of ``ce-``. + Content Mode + (https://github.com/cloudevents/spec/blob/main/cloudevents/bindings/http-protocol-binding.md#31-binary-content-mode). + In this representation, all fields except the ``data`` and + ``datacontenttype`` field on the message are mapped to HTTP + request headers with a prefix of ``ce-``. To construct the HTTP request payload and the value of the content-type HTTP header, the payload format is defined as @@ -315,8 +321,8 @@ class HttpEndpoint(proto.Message): - If a map named ``headers`` exists on the result of the expression, then its key/value pairs are directly mapped to the HTTP request headers. The headers values are - constructed from the corresponding value type’s canonical - representation. If the ``headers`` field doesn’t exist + constructed from the corresponding value type's canonical + representation. If the ``headers`` field doesn't exist then the resulting HTTP request will be the headers of the CloudEvent HTTP Binding Binary Content Mode representation of the final message. Note: If the specified binding @@ -366,6 +372,14 @@ class HttpEndpoint(proto.Message): "body": "new-body" } + - The default binding for the message payload can be + accessed using the ``body`` variable. It conatins a string + representation of the message payload in the format + specified by the ``output_payload_format`` field. If the + ``input_payload_format`` field is not set, the ``body`` + variable contains the same message payload bytes that were + published. + Additionally, the following CEL extension functions are provided for use in this CEL expression: @@ -420,40 +434,31 @@ class HttpEndpoint(proto.Message): - Converts a CEL list of CEL maps to a single CEL map - - toDestinationPayloadFormat(): - message.data.toDestinationPayloadFormat() -> string or - bytes - - - Converts the message data to the destination payload - format specified in - Pipeline.Destination.output_payload_format - - This function is meant to be applied to the message.data - field. - - If the destination payload format is not set, the - function will return the message data unchanged. - - toCloudEventJsonWithPayloadFormat: message.toCloudEventJsonWithPayloadFormat() -> map - Converts a message to the corresponding structure of - JSON format for CloudEvents - - This function applies toDestinationPayloadFormat() to - the message data. It also sets the corresponding - datacontenttype of the CloudEvent, as indicated by - Pipeline.Destination.output_payload_format. If no - output_payload_format is set it will use the existing - datacontenttype on the CloudEvent if present, else leave - datacontenttype absent. + JSON format for CloudEvents. + - It converts ``data`` to destination payload format + specified in ``output_payload_format``. If + ``output_payload_format`` is not set, the data will + remain unchanged. + - It also sets the corresponding datacontenttype of the + CloudEvent, as indicated by ``output_payload_format``. + If no ``output_payload_format`` is set it will use the + value of the "datacontenttype" attribute on the + CloudEvent if present, else remove "datacontenttype" + attribute. - This function expects that the content of the message will adhere to the standard CloudEvent format. If it - doesn’t then this function will fail. + doesn't then this function will fail. - The result is a CEL map that corresponds to the JSON representation of the CloudEvent. To convert that data to a JSON string it can be chained with the toJsonString function. The Pipeline expects that the message it receives adheres to - the standard CloudEvent format. If it doesn’t then the + the standard CloudEvent format. If it doesn't then the outgoing message request may fail with a persistent error. """ @@ -479,8 +484,8 @@ class AuthenticationConfig(proto.Message): Attributes: google_oidc (google.cloud.eventarc_v1.types.Pipeline.Destination.AuthenticationConfig.OidcToken): Optional. This authenticate method will apply - Google OIDC tokens signed by a GCP service - account to the requests. + Google OIDC tokens signed by a Google Cloud + service account to the requests. This field is a member of `oneof`_ ``authentication_method_descriptor``. oauth_token (google.cloud.eventarc_v1.types.Pipeline.Destination.AuthenticationConfig.OAuthToken): @@ -497,20 +502,23 @@ class AuthenticationConfig(proto.Message): class OidcToken(proto.Message): r"""Represents a config used to authenticate with a Google OIDC - token using a GCP service account. Use this authentication - method to invoke your Cloud Run and Cloud Functions destinations - or HTTP endpoints that support Google OIDC. + token using a Google Cloud service account. Use this + authentication method to invoke your Cloud Run and Cloud + Functions destinations or HTTP endpoints that support Google + OIDC. Attributes: service_account (str): - Required. Service account email used to generate the OIDC - Token. The principal who calls this API must have - iam.serviceAccounts.actAs permission in the service account. - See - https://cloud.google.com/iam/docs/understanding-service-accounts?hl=en#sa_common - for more information. Eventarc service agents must have - roles/roles/iam.serviceAccountTokenCreator role to allow the - Pipeline to create OpenID tokens for authenticated requests. + Required. Service account email used to + generate the OIDC Token. The principal who calls + this API must have iam.serviceAccounts.actAs + permission in the service account. See + https://cloud.google.com/iam/docs/understanding-service-accounts + for more information. Eventarc service agents + must have + roles/roles/iam.serviceAccountTokenCreator role + to allow the Pipeline to create OpenID tokens + for authenticated requests. audience (str): Optional. Audience to be used to generate the OIDC Token. The audience claim identifies the @@ -540,7 +548,7 @@ class OAuthToken(proto.Message): The principal who calls this API must have iam.serviceAccounts.actAs permission in the service account. See - https://cloud.google.com/iam/docs/understanding-service-accounts?hl=en#sa_common + https://cloud.google.com/iam/docs/understanding-service-accounts for more information. Eventarc service agents must have roles/roles/iam.serviceAccountTokenCreator role to allow Pipeline to create OAuth2 tokens for authenticated requests. @@ -708,7 +716,7 @@ class Transformation(proto.Message): datacontenttype absent. - This function expects that the content of the message will adhere to the standard CloudEvent format. If it - doesn’t then this function will fail. + doesn't then this function will fail. - The result is a CEL map that corresponds to the JSON representation of the CloudEvent. To convert that data to a JSON string it can be chained with the toJsonString @@ -835,6 +843,10 @@ class RetryPolicy(proto.Message): proto.STRING, number=99, ) + satisfies_pzs: bool = proto.Field( + proto.BOOL, + number=14, + ) __all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-cloud-eventarc/google/cloud/eventarc_v1/types/trigger.py b/packages/google-cloud-eventarc/google/cloud/eventarc_v1/types/trigger.py index 2dc2ebc5d7f3..324b3bbb23f8 100644 --- a/packages/google-cloud-eventarc/google/cloud/eventarc_v1/types/trigger.py +++ b/packages/google-cloud-eventarc/google/cloud/eventarc_v1/types/trigger.py @@ -468,7 +468,7 @@ class HttpEndpoint(proto.Message): Attributes: uri (str): - Required. The URI of the HTTP enpdoint. + Required. The URI of the HTTP endpoint. The value must be a RFC2396 URI string. Examples: ``http://10.10.10.8:80/route``, diff --git a/packages/google-cloud-eventarc/tests/unit/gapic/eventarc_v1/test_eventarc.py b/packages/google-cloud-eventarc/tests/unit/gapic/eventarc_v1/test_eventarc.py index 6165bd4c8308..490e6fa628c4 100644 --- a/packages/google-cloud-eventarc/tests/unit/gapic/eventarc_v1/test_eventarc.py +++ b/packages/google-cloud-eventarc/tests/unit/gapic/eventarc_v1/test_eventarc.py @@ -12556,6 +12556,7 @@ def test_get_pipeline(request_type, transport: str = "grpc"): display_name="display_name_value", crypto_key_name="crypto_key_name_value", etag="etag_value", + satisfies_pzs=True, ) response = client.get_pipeline(request) @@ -12572,6 +12573,7 @@ def test_get_pipeline(request_type, transport: str = "grpc"): assert response.display_name == "display_name_value" assert response.crypto_key_name == "crypto_key_name_value" assert response.etag == "etag_value" + assert response.satisfies_pzs is True def test_get_pipeline_non_empty_request_with_auto_populated_field(): @@ -12702,6 +12704,7 @@ async def test_get_pipeline_async( display_name="display_name_value", crypto_key_name="crypto_key_name_value", etag="etag_value", + satisfies_pzs=True, ) ) response = await client.get_pipeline(request) @@ -12719,6 +12722,7 @@ async def test_get_pipeline_async( assert response.display_name == "display_name_value" assert response.crypto_key_name == "crypto_key_name_value" assert response.etag == "etag_value" + assert response.satisfies_pzs is True @pytest.mark.asyncio @@ -26247,6 +26251,7 @@ async def test_get_pipeline_empty_call_grpc_asyncio(): display_name="display_name_value", crypto_key_name="crypto_key_name_value", etag="etag_value", + satisfies_pzs=True, ) ) await client.get_pipeline(request=None) @@ -27650,6 +27655,7 @@ def test_create_channel_rest_call_success(request_type): "activation_token": "activation_token_value", "crypto_key_name": "crypto_key_name_value", "satisfies_pzs": True, + "labels": {}, } # The version of a generated dependency at test runtime may differ from the version used during generation. # Delete any fields which are not present in the current runtime dependency @@ -27850,6 +27856,7 @@ def test_update_channel_rest_call_success(request_type): "activation_token": "activation_token_value", "crypto_key_name": "crypto_key_name_value", "satisfies_pzs": True, + "labels": {}, } # The version of a generated dependency at test runtime may differ from the version used during generation. # Delete any fields which are not present in the current runtime dependency @@ -28682,6 +28689,7 @@ def test_create_channel_connection_rest_call_success(request_type): "create_time": {"seconds": 751, "nanos": 543}, "update_time": {}, "activation_token": "activation_token_value", + "labels": {}, } # The version of a generated dependency at test runtime may differ from the version used during generation. # Delete any fields which are not present in the current runtime dependency @@ -29145,6 +29153,7 @@ def test_update_google_channel_config_rest_call_success(request_type): "name": "projects/sample1/locations/sample2/googleChannelConfig", "update_time": {"seconds": 751, "nanos": 543}, "crypto_key_name": "crypto_key_name_value", + "labels": {}, } # The version of a generated dependency at test runtime may differ from the version used during generation. # Delete any fields which are not present in the current runtime dependency @@ -31070,6 +31079,7 @@ def test_get_pipeline_rest_call_success(request_type): display_name="display_name_value", crypto_key_name="crypto_key_name_value", etag="etag_value", + satisfies_pzs=True, ) # Wrap the value into a proper Response obj @@ -31091,6 +31101,7 @@ def test_get_pipeline_rest_call_success(request_type): assert response.display_name == "display_name_value" assert response.crypto_key_name == "crypto_key_name_value" assert response.etag == "etag_value" + assert response.satisfies_pzs is True @pytest.mark.parametrize("null_interceptor", [True, False]) @@ -31364,6 +31375,7 @@ def test_create_pipeline_rest_call_success(request_type): "max_retry_delay": {}, }, "etag": "etag_value", + "satisfies_pzs": True, } # The version of a generated dependency at test runtime may differ from the version used during generation. # Delete any fields which are not present in the current runtime dependency @@ -31604,6 +31616,7 @@ def test_update_pipeline_rest_call_success(request_type): "max_retry_delay": {}, }, "etag": "etag_value", + "satisfies_pzs": True, } # The version of a generated dependency at test runtime may differ from the version used during generation. # Delete any fields which are not present in the current runtime dependency diff --git a/packages/google-cloud-video-live-stream/.OwlBot.yaml b/packages/google-cloud-video-live-stream/.OwlBot.yaml deleted file mode 100644 index b70fb515e982..000000000000 --- a/packages/google-cloud-video-live-stream/.OwlBot.yaml +++ /dev/null @@ -1,24 +0,0 @@ -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - - -deep-remove-regex: - - /owl-bot-staging - -deep-copy-regex: - - source: /google/cloud/video/livestream/(v.*)/.*-py - dest: /owl-bot-staging/google-cloud-video-live-stream/$1 - -begin-after-commit-hash: 70f7f0525414fe4dfeb2fc2e81546b073f83a621 -api-name: google-cloud-video-live-stream 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 29105de674f2..6cad775f7751 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 @@ -26,12 +26,16 @@ ) from google.cloud.video.live_stream_v1.types.outputs import ( AudioStream, + Distribution, + DistributionStream, ElementaryStream, Manifest, MuxStream, PreprocessingConfig, + RtmpPushOutputEndpoint, SegmentSettings, SpriteSheet, + SrtPushOutputEndpoint, TextStream, TimecodeConfig, VideoStream, @@ -40,10 +44,12 @@ Asset, AudioFormat, AudioStreamProperty, + AutoTranscriptionConfig, Channel, Clip, DvrSession, Encryption, + EncryptionUpdate, Event, Input, InputAttachment, @@ -93,8 +99,12 @@ ListInputsRequest, ListInputsResponse, OperationMetadata, + PreviewInputRequest, + PreviewInputResponse, StartChannelRequest, + StartDistributionRequest, StopChannelRequest, + StopDistributionRequest, UpdateChannelRequest, UpdateDvrSessionRequest, UpdateInputRequest, @@ -105,22 +115,28 @@ "LivestreamServiceClient", "LivestreamServiceAsyncClient", "AudioStream", + "Distribution", + "DistributionStream", "ElementaryStream", "Manifest", "MuxStream", "PreprocessingConfig", + "RtmpPushOutputEndpoint", "SegmentSettings", "SpriteSheet", + "SrtPushOutputEndpoint", "TextStream", "TimecodeConfig", "VideoStream", "Asset", "AudioFormat", "AudioStreamProperty", + "AutoTranscriptionConfig", "Channel", "Clip", "DvrSession", "Encryption", + "EncryptionUpdate", "Event", "Input", "InputAttachment", @@ -168,8 +184,12 @@ "ListInputsRequest", "ListInputsResponse", "OperationMetadata", + "PreviewInputRequest", + "PreviewInputResponse", "StartChannelRequest", + "StartDistributionRequest", "StopChannelRequest", + "StopDistributionRequest", "UpdateChannelRequest", "UpdateDvrSessionRequest", "UpdateInputRequest", 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 b4011c0a5a56..70fa7d19bed2 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 @@ -24,12 +24,16 @@ ) from .types.outputs import ( AudioStream, + Distribution, + DistributionStream, ElementaryStream, Manifest, MuxStream, PreprocessingConfig, + RtmpPushOutputEndpoint, SegmentSettings, SpriteSheet, + SrtPushOutputEndpoint, TextStream, TimecodeConfig, VideoStream, @@ -38,10 +42,12 @@ Asset, AudioFormat, AudioStreamProperty, + AutoTranscriptionConfig, Channel, Clip, DvrSession, Encryption, + EncryptionUpdate, Event, Input, InputAttachment, @@ -91,8 +97,12 @@ ListInputsRequest, ListInputsResponse, OperationMetadata, + PreviewInputRequest, + PreviewInputResponse, StartChannelRequest, + StartDistributionRequest, StopChannelRequest, + StopDistributionRequest, UpdateChannelRequest, UpdateDvrSessionRequest, UpdateInputRequest, @@ -105,6 +115,7 @@ "AudioFormat", "AudioStream", "AudioStreamProperty", + "AutoTranscriptionConfig", "Channel", "ChannelOperationResponse", "Clip", @@ -120,9 +131,12 @@ "DeleteDvrSessionRequest", "DeleteEventRequest", "DeleteInputRequest", + "Distribution", + "DistributionStream", "DvrSession", "ElementaryStream", "Encryption", + "EncryptionUpdate", "Event", "GetAssetRequest", "GetChannelRequest", @@ -156,12 +170,18 @@ "OperationMetadata", "Pool", "PreprocessingConfig", + "PreviewInputRequest", + "PreviewInputResponse", "RetentionConfig", + "RtmpPushOutputEndpoint", "SegmentSettings", "SpriteSheet", + "SrtPushOutputEndpoint", "StartChannelRequest", + "StartDistributionRequest", "StaticOverlay", "StopChannelRequest", + "StopDistributionRequest", "TextStream", "TimeInterval", "TimecodeConfig", 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 d94a38f317f9..1f2ccfe728ea 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 @@ -135,16 +135,31 @@ "list_inputs" ] }, + "PreviewInput": { + "methods": [ + "preview_input" + ] + }, "StartChannel": { "methods": [ "start_channel" ] }, + "StartDistribution": { + "methods": [ + "start_distribution" + ] + }, "StopChannel": { "methods": [ "stop_channel" ] }, + "StopDistribution": { + "methods": [ + "stop_distribution" + ] + }, "UpdateChannel": { "methods": [ "update_channel" @@ -295,16 +310,31 @@ "list_inputs" ] }, + "PreviewInput": { + "methods": [ + "preview_input" + ] + }, "StartChannel": { "methods": [ "start_channel" ] }, + "StartDistribution": { + "methods": [ + "start_distribution" + ] + }, "StopChannel": { "methods": [ "stop_channel" ] }, + "StopDistribution": { + "methods": [ + "stop_distribution" + ] + }, "UpdateChannel": { "methods": [ "update_channel" @@ -455,16 +485,31 @@ "list_inputs" ] }, + "PreviewInput": { + "methods": [ + "preview_input" + ] + }, "StartChannel": { "methods": [ "start_channel" ] }, + "StartDistribution": { + "methods": [ + "start_distribution" + ] + }, "StopChannel": { "methods": [ "stop_channel" ] }, + "StopDistribution": { + "methods": [ + "stop_distribution" + ] + }, "UpdateChannel": { "methods": [ "update_channel" 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 8537b8956ced..1c990ace78ed 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 @@ -391,8 +391,12 @@ async def sample_create_channel(): should not be set. channel_id (:class:`str`): Required. The ID of the channel resource to be created. - This value must be 1-63 characters, begin and end with - ``[a-z0-9]``, could contain dashes (-) in between. + + This value must be 1-63 characters, begin and end with a + lower-case letter or a number, and consist of only + lower-case letters, numbers, and hyphens. In other + words, it must match the following regex: + ``^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$``. This corresponds to the ``channel_id`` field on the ``request`` instance; if ``request`` is provided, this @@ -1278,6 +1282,289 @@ async def sample_stop_channel(): # Done; return the response. return response + async def start_distribution( + self, + request: Optional[Union[service.StartDistributionRequest, dict]] = None, + *, + name: Optional[str] = None, + distribution_keys: Optional[MutableSequence[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"""Starts distribution which delivers outputs to the + destination indicated by the Distribution configuration. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying 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_start_distribution(): + # Create a client + client = live_stream_v1.LivestreamServiceAsyncClient() + + # Initialize request argument(s) + request = live_stream_v1.StartDistributionRequest( + name="name_value", + ) + + # Make the request + operation = client.start_distribution(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.StartDistributionRequest, dict]]): + The request object. Request message for + "LivestreamService.StartDistribution". + name (:class:`str`): + Required. The name of the channel resource, in the form + of: + ``projects/{project}/locations/{location}/channels/{channelId}``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + distribution_keys (:class:`MutableSequence[str]`): + Optional. A list of keys to identify + the distribution configuration in the + channel resource. If left empty, all the + distributions in the channel + specification will be started. + + This corresponds to the ``distribution_keys`` 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.ChannelOperationResponse` + Response message for Start/Stop Channel long-running + operations. + + """ + # Create or coerce a protobuf request 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, distribution_keys] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request 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.StartDistributionRequest): + request = service.StartDistributionRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + if distribution_keys: + request.distribution_keys.extend(distribution_keys) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.start_distribution + ] + + # 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, + service.ChannelOperationResponse, + metadata_type=service.OperationMetadata, + ) + + # Done; return the response. + return response + + async def stop_distribution( + self, + request: Optional[Union[service.StopDistributionRequest, dict]] = None, + *, + name: Optional[str] = None, + distribution_keys: Optional[MutableSequence[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"""Stops the specified distribution. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying 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_stop_distribution(): + # Create a client + client = live_stream_v1.LivestreamServiceAsyncClient() + + # Initialize request argument(s) + request = live_stream_v1.StopDistributionRequest( + name="name_value", + ) + + # Make the request + operation = client.stop_distribution(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.StopDistributionRequest, dict]]): + The request object. Request message for + "LivestreamService.StopDistribution". + name (:class:`str`): + Required. The name of the channel resource, in the form + of: + ``projects/{project}/locations/{location}/channels/{channelId}``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + distribution_keys (:class:`MutableSequence[str]`): + Optional. A list of key to identify + the distribution configuration in the + channel resource. If left empty, all the + distributions in the channel + specification will be stopped. + + This corresponds to the ``distribution_keys`` 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.ChannelOperationResponse` + Response message for Start/Stop Channel long-running + operations. + + """ + # Create or coerce a protobuf request 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, distribution_keys] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request 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.StopDistributionRequest): + request = service.StopDistributionRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + if distribution_keys: + request.distribution_keys.extend(distribution_keys) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.stop_distribution + ] + + # 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, + service.ChannelOperationResponse, + metadata_type=service.OperationMetadata, + ) + + # Done; return the response. + return response + async def create_input( self, request: Optional[Union[service.CreateInputRequest, dict]] = None, @@ -1343,8 +1630,12 @@ async def sample_create_input(): should not be set. input_id (:class:`str`): Required. The ID of the input resource to be created. - This value must be 1-63 characters, begin and end with - ``[a-z0-9]``, could contain dashes (-) in between. + + This value must be 1-63 characters, begin and end with a + lower-case letter or a number, and consist of only + lower-case letters, numbers, and hyphens. In other + words, it must match the following regex: + ``^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$``. This corresponds to the ``input_id`` field on the ``request`` instance; if ``request`` is provided, this @@ -1949,6 +2240,118 @@ async def sample_update_input(): # Done; return the response. return response + async def preview_input( + self, + request: Optional[Union[service.PreviewInputRequest, 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]]] = (), + ) -> service.PreviewInputResponse: + r"""Preview the streaming content of the specified input. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying 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_preview_input(): + # Create a client + client = live_stream_v1.LivestreamServiceAsyncClient() + + # Initialize request argument(s) + request = live_stream_v1.PreviewInputRequest( + name="name_value", + ) + + # Make the request + response = await client.preview_input(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.video.live_stream_v1.types.PreviewInputRequest, dict]]): + The request object. Request message for + "LivestreamService.PreviewInput". + name (:class:`str`): + Required. The name of the input resource, in the form + of: + ``projects/{project}/locations/{location}/inputs/{inputId}``. + + 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.PreviewInputResponse: + Response message for + "LivestreamService.PreviewInput" + + """ + # Create or coerce a protobuf request 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.PreviewInputRequest): + request = service.PreviewInputRequest(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.preview_input + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + async def create_event( self, request: Optional[Union[service.CreateEventRequest, dict]] = None, @@ -2011,8 +2414,12 @@ async def sample_create_event(): should not be set. event_id (:class:`str`): Required. The ID of the event resource to be created. - This value must be 1-63 characters, begin and end with - ``[a-z0-9]``, could contain dashes (-) in between. + + This value must be 1-63 characters, begin and end with a + lower-case letter or a number, and consist of only + lower-case letters, numbers, and hyphens. In other + words, it must match the following regex: + ``^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$``. This corresponds to the ``event_id`` field on the ``request`` instance; if ``request`` is provided, this @@ -2733,13 +3140,13 @@ async def sample_create_clip(): on the ``request`` instance; if ``request`` is provided, this should not be set. clip_id (:class:`str`): - Required. Id of the requesting object - in the following form: + Required. The ID of the clip resource to be created. - 1. 1 character minimum, 63 characters - maximum - 2. Only contains letters, digits, - underscores, and hyphens + This value must be 1-63 characters, begin and end with a + lower-case letter or a number, and consist of only + lower-case letters, numbers, and hyphens. In other + words, it must match the following regex: + ``^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$``. This corresponds to the ``clip_id`` field on the ``request`` instance; if ``request`` is provided, this @@ -3024,13 +3431,14 @@ async def sample_create_dvr_session(): 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: + Required. The ID of the DVR session resource to be + created. - 1. 1 character minimum, 63 characters - maximum - 2. Only contains letters, digits, - underscores, and hyphens + This value must be 1-63 characters, begin and end with a + lower-case letter or a number, and consist of only + lower-case letters, numbers, and hyphens. In other + words, it must match the following regex: + ``^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$``. This corresponds to the ``dvr_session_id`` field on the ``request`` instance; if ``request`` is provided, this @@ -3700,8 +4108,12 @@ async def sample_create_asset(): should not be set. asset_id (:class:`str`): Required. The ID of the asset resource to be created. - This value must be 1-63 characters, begin and end with - ``[a-z0-9]``, could contain dashes (-) in between. + + This value must be 1-63 characters, begin and end with a + lower-case letter or a number, and consist of only + lower-case letters, numbers, and hyphens. In other + words, it must match the following regex: + ``^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$``. This corresponds to the ``asset_id`` field on the ``request`` instance; if ``request`` is provided, this 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 5bb798f065bc..baed13014fa9 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 @@ -974,8 +974,12 @@ def sample_create_channel(): should not be set. channel_id (str): Required. The ID of the channel resource to be created. - This value must be 1-63 characters, begin and end with - ``[a-z0-9]``, could contain dashes (-) in between. + + This value must be 1-63 characters, begin and end with a + lower-case letter or a number, and consist of only + lower-case letters, numbers, and hyphens. In other + words, it must match the following regex: + ``^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$``. This corresponds to the ``channel_id`` field on the ``request`` instance; if ``request`` is provided, this @@ -1840,6 +1844,283 @@ def sample_stop_channel(): # Done; return the response. return response + def start_distribution( + self, + request: Optional[Union[service.StartDistributionRequest, dict]] = None, + *, + name: Optional[str] = None, + distribution_keys: Optional[MutableSequence[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"""Starts distribution which delivers outputs to the + destination indicated by the Distribution configuration. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying 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_start_distribution(): + # Create a client + client = live_stream_v1.LivestreamServiceClient() + + # Initialize request argument(s) + request = live_stream_v1.StartDistributionRequest( + name="name_value", + ) + + # Make the request + operation = client.start_distribution(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.StartDistributionRequest, dict]): + The request object. Request message for + "LivestreamService.StartDistribution". + name (str): + Required. The name of the channel resource, in the form + of: + ``projects/{project}/locations/{location}/channels/{channelId}``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + distribution_keys (MutableSequence[str]): + Optional. A list of keys to identify + the distribution configuration in the + channel resource. If left empty, all the + distributions in the channel + specification will be started. + + This corresponds to the ``distribution_keys`` 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.ChannelOperationResponse` + Response message for Start/Stop Channel long-running + operations. + + """ + # Create or coerce a protobuf request 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, distribution_keys] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request 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.StartDistributionRequest): + request = service.StartDistributionRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + if distribution_keys is not None: + request.distribution_keys = distribution_keys + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.start_distribution] + + # 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, + service.ChannelOperationResponse, + metadata_type=service.OperationMetadata, + ) + + # Done; return the response. + return response + + def stop_distribution( + self, + request: Optional[Union[service.StopDistributionRequest, dict]] = None, + *, + name: Optional[str] = None, + distribution_keys: Optional[MutableSequence[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"""Stops the specified distribution. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying 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_stop_distribution(): + # Create a client + client = live_stream_v1.LivestreamServiceClient() + + # Initialize request argument(s) + request = live_stream_v1.StopDistributionRequest( + name="name_value", + ) + + # Make the request + operation = client.stop_distribution(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.StopDistributionRequest, dict]): + The request object. Request message for + "LivestreamService.StopDistribution". + name (str): + Required. The name of the channel resource, in the form + of: + ``projects/{project}/locations/{location}/channels/{channelId}``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + distribution_keys (MutableSequence[str]): + Optional. A list of key to identify + the distribution configuration in the + channel resource. If left empty, all the + distributions in the channel + specification will be stopped. + + This corresponds to the ``distribution_keys`` 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.ChannelOperationResponse` + Response message for Start/Stop Channel long-running + operations. + + """ + # Create or coerce a protobuf request 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, distribution_keys] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request 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.StopDistributionRequest): + request = service.StopDistributionRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + if distribution_keys is not None: + request.distribution_keys = distribution_keys + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.stop_distribution] + + # 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, + service.ChannelOperationResponse, + metadata_type=service.OperationMetadata, + ) + + # Done; return the response. + return response + def create_input( self, request: Optional[Union[service.CreateInputRequest, dict]] = None, @@ -1905,8 +2186,12 @@ def sample_create_input(): should not be set. input_id (str): Required. The ID of the input resource to be created. - This value must be 1-63 characters, begin and end with - ``[a-z0-9]``, could contain dashes (-) in between. + + This value must be 1-63 characters, begin and end with a + lower-case letter or a number, and consist of only + lower-case letters, numbers, and hyphens. In other + words, it must match the following regex: + ``^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$``. This corresponds to the ``input_id`` field on the ``request`` instance; if ``request`` is provided, this @@ -2496,6 +2781,115 @@ def sample_update_input(): # Done; return the response. return response + def preview_input( + self, + request: Optional[Union[service.PreviewInputRequest, 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]]] = (), + ) -> service.PreviewInputResponse: + r"""Preview the streaming content of the specified input. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying 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_preview_input(): + # Create a client + client = live_stream_v1.LivestreamServiceClient() + + # Initialize request argument(s) + request = live_stream_v1.PreviewInputRequest( + name="name_value", + ) + + # Make the request + response = client.preview_input(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.video.live_stream_v1.types.PreviewInputRequest, dict]): + The request object. Request message for + "LivestreamService.PreviewInput". + name (str): + Required. The name of the input resource, in the form + of: + ``projects/{project}/locations/{location}/inputs/{inputId}``. + + 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.PreviewInputResponse: + Response message for + "LivestreamService.PreviewInput" + + """ + # Create or coerce a protobuf request 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.PreviewInputRequest): + request = service.PreviewInputRequest(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.preview_input] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + def create_event( self, request: Optional[Union[service.CreateEventRequest, dict]] = None, @@ -2558,8 +2952,12 @@ def sample_create_event(): should not be set. event_id (str): Required. The ID of the event resource to be created. - This value must be 1-63 characters, begin and end with - ``[a-z0-9]``, could contain dashes (-) in between. + + This value must be 1-63 characters, begin and end with a + lower-case letter or a number, and consist of only + lower-case letters, numbers, and hyphens. In other + words, it must match the following regex: + ``^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$``. This corresponds to the ``event_id`` field on the ``request`` instance; if ``request`` is provided, this @@ -3264,13 +3662,13 @@ def sample_create_clip(): on the ``request`` instance; if ``request`` is provided, this should not be set. clip_id (str): - Required. Id of the requesting object - in the following form: + Required. The ID of the clip resource to be created. - 1. 1 character minimum, 63 characters - maximum - 2. Only contains letters, digits, - underscores, and hyphens + This value must be 1-63 characters, begin and end with a + lower-case letter or a number, and consist of only + lower-case letters, numbers, and hyphens. In other + words, it must match the following regex: + ``^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$``. This corresponds to the ``clip_id`` field on the ``request`` instance; if ``request`` is provided, this @@ -3549,13 +3947,14 @@ def sample_create_dvr_session(): 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: + Required. The ID of the DVR session resource to be + created. - 1. 1 character minimum, 63 characters - maximum - 2. Only contains letters, digits, - underscores, and hyphens + This value must be 1-63 characters, begin and end with a + lower-case letter or a number, and consist of only + lower-case letters, numbers, and hyphens. In other + words, it must match the following regex: + ``^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$``. This corresponds to the ``dvr_session_id`` field on the ``request`` instance; if ``request`` is provided, this @@ -4210,8 +4609,12 @@ def sample_create_asset(): should not be set. asset_id (str): Required. The ID of the asset resource to be created. - This value must be 1-63 characters, begin and end with - ``[a-z0-9]``, could contain dashes (-) in between. + + This value must be 1-63 characters, begin and end with a + lower-case letter or a number, and consist of only + lower-case letters, numbers, and hyphens. In other + words, it must match the following regex: + ``^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$``. This corresponds to the ``asset_id`` field on the ``request`` instance; if ``request`` is provided, this 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 8bc296610394..cc5e521cb668 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 @@ -188,6 +188,16 @@ def _prep_wrapped_messages(self, client_info): default_timeout=60.0, client_info=client_info, ), + self.start_distribution: gapic_v1.method.wrap_method( + self.start_distribution, + default_timeout=60.0, + client_info=client_info, + ), + self.stop_distribution: gapic_v1.method.wrap_method( + self.stop_distribution, + default_timeout=60.0, + client_info=client_info, + ), self.create_input: gapic_v1.method.wrap_method( self.create_input, default_timeout=60.0, @@ -231,6 +241,11 @@ def _prep_wrapped_messages(self, client_info): default_timeout=60.0, client_info=client_info, ), + self.preview_input: gapic_v1.method.wrap_method( + self.preview_input, + default_timeout=60.0, + client_info=client_info, + ), self.create_event: gapic_v1.method.wrap_method( self.create_event, default_timeout=60.0, @@ -299,47 +314,65 @@ def _prep_wrapped_messages(self, client_info): ), self.create_clip: gapic_v1.method.wrap_method( self.create_clip, - default_timeout=None, + default_timeout=60.0, client_info=client_info, ), self.delete_clip: gapic_v1.method.wrap_method( self.delete_clip, - default_timeout=None, + default_timeout=60.0, client_info=client_info, ), self.create_dvr_session: gapic_v1.method.wrap_method( self.create_dvr_session, - default_timeout=None, + default_timeout=60.0, client_info=client_info, ), self.list_dvr_sessions: gapic_v1.method.wrap_method( self.list_dvr_sessions, - 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_dvr_session: gapic_v1.method.wrap_method( self.get_dvr_session, - 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.delete_dvr_session: gapic_v1.method.wrap_method( self.delete_dvr_session, - default_timeout=None, + default_timeout=60.0, client_info=client_info, ), self.update_dvr_session: gapic_v1.method.wrap_method( self.update_dvr_session, - default_timeout=None, + default_timeout=60.0, client_info=client_info, ), self.create_asset: gapic_v1.method.wrap_method( self.create_asset, - default_timeout=None, + default_timeout=60.0, client_info=client_info, ), self.delete_asset: gapic_v1.method.wrap_method( self.delete_asset, - default_timeout=None, + default_timeout=60.0, client_info=client_info, ), self.get_asset: gapic_v1.method.wrap_method( @@ -386,7 +419,7 @@ def _prep_wrapped_messages(self, client_info): ), self.update_pool: gapic_v1.method.wrap_method( self.update_pool, - default_timeout=None, + default_timeout=60.0, client_info=client_info, ), self.get_location: gapic_v1.method.wrap_method( @@ -498,6 +531,24 @@ def stop_channel( ]: raise NotImplementedError() + @property + def start_distribution( + self, + ) -> Callable[ + [service.StartDistributionRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + + @property + def stop_distribution( + self, + ) -> Callable[ + [service.StopDistributionRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + @property def create_input( self, @@ -542,6 +593,15 @@ def update_input( ]: raise NotImplementedError() + @property + def preview_input( + self, + ) -> Callable[ + [service.PreviewInputRequest], + Union[service.PreviewInputResponse, Awaitable[service.PreviewInputResponse]], + ]: + raise NotImplementedError() + @property def create_event( 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 40587679f184..c26226f05db4 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 @@ -530,6 +530,59 @@ def stop_channel( ) return self._stubs["stop_channel"] + @property + def start_distribution( + self, + ) -> Callable[[service.StartDistributionRequest], operations_pb2.Operation]: + r"""Return a callable for the start distribution method over gRPC. + + Starts distribution which delivers outputs to the + destination indicated by the Distribution configuration. + + Returns: + Callable[[~.StartDistributionRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "start_distribution" not in self._stubs: + self._stubs["start_distribution"] = self._logged_channel.unary_unary( + "/google.cloud.video.livestream.v1.LivestreamService/StartDistribution", + request_serializer=service.StartDistributionRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["start_distribution"] + + @property + def stop_distribution( + self, + ) -> Callable[[service.StopDistributionRequest], operations_pb2.Operation]: + r"""Return a callable for the stop distribution method over gRPC. + + Stops the specified distribution. + + Returns: + Callable[[~.StopDistributionRequest], + ~.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 "stop_distribution" not in self._stubs: + self._stubs["stop_distribution"] = self._logged_channel.unary_unary( + "/google.cloud.video.livestream.v1.LivestreamService/StopDistribution", + request_serializer=service.StopDistributionRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["stop_distribution"] + @property def create_input( self, @@ -659,6 +712,32 @@ def update_input( ) return self._stubs["update_input"] + @property + def preview_input( + self, + ) -> Callable[[service.PreviewInputRequest], service.PreviewInputResponse]: + r"""Return a callable for the preview input method over gRPC. + + Preview the streaming content of the specified input. + + Returns: + Callable[[~.PreviewInputRequest], + ~.PreviewInputResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "preview_input" not in self._stubs: + self._stubs["preview_input"] = self._logged_channel.unary_unary( + "/google.cloud.video.livestream.v1.LivestreamService/PreviewInput", + request_serializer=service.PreviewInputRequest.serialize, + response_deserializer=service.PreviewInputResponse.deserialize, + ) + return self._stubs["preview_input"] + @property def create_event(self) -> Callable[[service.CreateEventRequest], resources.Event]: r"""Return a callable for the create event method over gRPC. 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 de70f0752978..f65bd1a8e28a 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 @@ -542,6 +542,63 @@ def stop_channel( ) return self._stubs["stop_channel"] + @property + def start_distribution( + self, + ) -> Callable[ + [service.StartDistributionRequest], Awaitable[operations_pb2.Operation] + ]: + r"""Return a callable for the start distribution method over gRPC. + + Starts distribution which delivers outputs to the + destination indicated by the Distribution configuration. + + Returns: + Callable[[~.StartDistributionRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "start_distribution" not in self._stubs: + self._stubs["start_distribution"] = self._logged_channel.unary_unary( + "/google.cloud.video.livestream.v1.LivestreamService/StartDistribution", + request_serializer=service.StartDistributionRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["start_distribution"] + + @property + def stop_distribution( + self, + ) -> Callable[ + [service.StopDistributionRequest], Awaitable[operations_pb2.Operation] + ]: + r"""Return a callable for the stop distribution method over gRPC. + + Stops the specified distribution. + + Returns: + Callable[[~.StopDistributionRequest], + 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 "stop_distribution" not in self._stubs: + self._stubs["stop_distribution"] = self._logged_channel.unary_unary( + "/google.cloud.video.livestream.v1.LivestreamService/StopDistribution", + request_serializer=service.StopDistributionRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["stop_distribution"] + @property def create_input( self, @@ -673,6 +730,34 @@ def update_input( ) return self._stubs["update_input"] + @property + def preview_input( + self, + ) -> Callable[ + [service.PreviewInputRequest], Awaitable[service.PreviewInputResponse] + ]: + r"""Return a callable for the preview input method over gRPC. + + Preview the streaming content of the specified input. + + Returns: + Callable[[~.PreviewInputRequest], + Awaitable[~.PreviewInputResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "preview_input" not in self._stubs: + self._stubs["preview_input"] = self._logged_channel.unary_unary( + "/google.cloud.video.livestream.v1.LivestreamService/PreviewInput", + request_serializer=service.PreviewInputRequest.serialize, + response_deserializer=service.PreviewInputResponse.deserialize, + ) + return self._stubs["preview_input"] + @property def create_event( self, @@ -1235,6 +1320,16 @@ def _prep_wrapped_messages(self, client_info): default_timeout=60.0, client_info=client_info, ), + self.start_distribution: self._wrap_method( + self.start_distribution, + default_timeout=60.0, + client_info=client_info, + ), + self.stop_distribution: self._wrap_method( + self.stop_distribution, + default_timeout=60.0, + client_info=client_info, + ), self.create_input: self._wrap_method( self.create_input, default_timeout=60.0, @@ -1278,6 +1373,11 @@ def _prep_wrapped_messages(self, client_info): default_timeout=60.0, client_info=client_info, ), + self.preview_input: self._wrap_method( + self.preview_input, + default_timeout=60.0, + client_info=client_info, + ), self.create_event: self._wrap_method( self.create_event, default_timeout=60.0, @@ -1346,47 +1446,65 @@ def _prep_wrapped_messages(self, client_info): ), self.create_clip: self._wrap_method( self.create_clip, - default_timeout=None, + default_timeout=60.0, client_info=client_info, ), self.delete_clip: self._wrap_method( self.delete_clip, - default_timeout=None, + default_timeout=60.0, client_info=client_info, ), self.create_dvr_session: self._wrap_method( self.create_dvr_session, - default_timeout=None, + default_timeout=60.0, client_info=client_info, ), self.list_dvr_sessions: self._wrap_method( self.list_dvr_sessions, - 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_dvr_session: self._wrap_method( self.get_dvr_session, - 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.delete_dvr_session: self._wrap_method( self.delete_dvr_session, - default_timeout=None, + default_timeout=60.0, client_info=client_info, ), self.update_dvr_session: self._wrap_method( self.update_dvr_session, - default_timeout=None, + default_timeout=60.0, client_info=client_info, ), self.create_asset: self._wrap_method( self.create_asset, - default_timeout=None, + default_timeout=60.0, client_info=client_info, ), self.delete_asset: self._wrap_method( self.delete_asset, - default_timeout=None, + default_timeout=60.0, client_info=client_info, ), self.get_asset: self._wrap_method( @@ -1433,7 +1551,7 @@ def _prep_wrapped_messages(self, client_info): ), self.update_pool: self._wrap_method( self.update_pool, - default_timeout=None, + default_timeout=60.0, client_info=client_info, ), self.get_location: 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 1355d49fa914..05b57438eb7e 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 @@ -271,6 +271,14 @@ def post_list_inputs(self, response): logging.log(f"Received response: {response}") return response + def pre_preview_input(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_preview_input(self, response): + logging.log(f"Received response: {response}") + return response + def pre_start_channel(self, request, metadata): logging.log(f"Received request: {request}") return request, metadata @@ -279,6 +287,14 @@ def post_start_channel(self, response): logging.log(f"Received response: {response}") return response + def pre_start_distribution(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_start_distribution(self, response): + logging.log(f"Received response: {response}") + return response + def pre_stop_channel(self, request, metadata): logging.log(f"Received request: {request}") return request, metadata @@ -287,6 +303,14 @@ def post_stop_channel(self, response): logging.log(f"Received response: {response}") return response + def pre_stop_distribution(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_stop_distribution(self, response): + logging.log(f"Received response: {response}") + return response + def pre_update_channel(self, request, metadata): logging.log(f"Received request: {request}") return request, metadata @@ -1433,6 +1457,52 @@ def post_list_inputs_with_metadata( """ return response, metadata + def pre_preview_input( + self, + request: service.PreviewInputRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[service.PreviewInputRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for preview_input + + Override in a subclass to manipulate the request or metadata + before they are sent to the LivestreamService server. + """ + return request, metadata + + def post_preview_input( + self, response: service.PreviewInputResponse + ) -> service.PreviewInputResponse: + """Post-rpc interceptor for preview_input + + DEPRECATED. Please use the `post_preview_input_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_preview_input` interceptor runs + before the `post_preview_input_with_metadata` interceptor. + """ + return response + + def post_preview_input_with_metadata( + self, + response: service.PreviewInputResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[service.PreviewInputResponse, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for preview_input + + 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_preview_input_with_metadata` + interceptor in new development instead of the `post_preview_input` interceptor. + When both interceptors are used, this `post_preview_input_with_metadata` interceptor runs after the + `post_preview_input` interceptor. The (possibly modified) response returned by + `post_preview_input` will be passed to + `post_preview_input_with_metadata`. + """ + return response, metadata + def pre_start_channel( self, request: service.StartChannelRequest, @@ -1479,6 +1549,54 @@ def post_start_channel_with_metadata( """ return response, metadata + def pre_start_distribution( + self, + request: service.StartDistributionRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + service.StartDistributionRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for start_distribution + + Override in a subclass to manipulate the request or metadata + before they are sent to the LivestreamService server. + """ + return request, metadata + + def post_start_distribution( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for start_distribution + + DEPRECATED. Please use the `post_start_distribution_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_start_distribution` interceptor runs + before the `post_start_distribution_with_metadata` interceptor. + """ + return response + + def post_start_distribution_with_metadata( + self, + response: operations_pb2.Operation, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for start_distribution + + 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_start_distribution_with_metadata` + interceptor in new development instead of the `post_start_distribution` interceptor. + When both interceptors are used, this `post_start_distribution_with_metadata` interceptor runs after the + `post_start_distribution` interceptor. The (possibly modified) response returned by + `post_start_distribution` will be passed to + `post_start_distribution_with_metadata`. + """ + return response, metadata + def pre_stop_channel( self, request: service.StopChannelRequest, @@ -1525,6 +1643,54 @@ def post_stop_channel_with_metadata( """ return response, metadata + def pre_stop_distribution( + self, + request: service.StopDistributionRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + service.StopDistributionRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for stop_distribution + + Override in a subclass to manipulate the request or metadata + before they are sent to the LivestreamService server. + """ + return request, metadata + + def post_stop_distribution( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for stop_distribution + + DEPRECATED. Please use the `post_stop_distribution_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_stop_distribution` interceptor runs + before the `post_stop_distribution_with_metadata` interceptor. + """ + return response + + def post_stop_distribution_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 stop_distribution + + 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_stop_distribution_with_metadata` + interceptor in new development instead of the `post_stop_distribution` interceptor. + When both interceptors are used, this `post_stop_distribution_with_metadata` interceptor runs after the + `post_stop_distribution` interceptor. The (possibly modified) response returned by + `post_stop_distribution` will be passed to + `post_stop_distribution_with_metadata`. + """ + return response, metadata + def pre_update_channel( self, request: service.UpdateChannelRequest, @@ -5702,11 +5868,11 @@ def __call__( ) return resp - class _StartChannel( - _BaseLivestreamServiceRestTransport._BaseStartChannel, LivestreamServiceRestStub + class _PreviewInput( + _BaseLivestreamServiceRestTransport._BasePreviewInput, LivestreamServiceRestStub ): def __hash__(self): - return hash("LivestreamServiceRestTransport.StartChannel") + return hash("LivestreamServiceRestTransport.PreviewInput") @staticmethod def _get_response( @@ -5733,18 +5899,18 @@ def _get_response( def __call__( self, - request: service.StartChannelRequest, + request: service.PreviewInputRequest, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operations_pb2.Operation: - r"""Call the start channel method over HTTP. + ) -> service.PreviewInputResponse: + r"""Call the preview input method over HTTP. Args: - request (~.service.StartChannelRequest): + request (~.service.PreviewInputRequest): The request object. Request message for - "LivestreamService.StartChannel". + "LivestreamService.PreviewInput". retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -5754,28 +5920,27 @@ 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. + ~.service.PreviewInputResponse: + Response message for + "LivestreamService.PreviewInput" """ http_options = ( - _BaseLivestreamServiceRestTransport._BaseStartChannel._get_http_options() + _BaseLivestreamServiceRestTransport._BasePreviewInput._get_http_options() ) - request, metadata = self._interceptor.pre_start_channel(request, metadata) - transcoded_request = _BaseLivestreamServiceRestTransport._BaseStartChannel._get_transcoded_request( + request, metadata = self._interceptor.pre_preview_input(request, metadata) + transcoded_request = _BaseLivestreamServiceRestTransport._BasePreviewInput._get_transcoded_request( http_options, request ) - body = _BaseLivestreamServiceRestTransport._BaseStartChannel._get_request_body_json( + body = _BaseLivestreamServiceRestTransport._BasePreviewInput._get_request_body_json( transcoded_request ) # Jsonify the query params - query_params = _BaseLivestreamServiceRestTransport._BaseStartChannel._get_query_params_json( + query_params = _BaseLivestreamServiceRestTransport._BasePreviewInput._get_query_params_json( transcoded_request ) @@ -5787,7 +5952,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 = { @@ -5797,17 +5962,17 @@ def __call__( "headers": dict(metadata), } _LOGGER.debug( - f"Sending request for google.cloud.video.livestream_v1.LivestreamServiceClient.StartChannel", + f"Sending request for google.cloud.video.livestream_v1.LivestreamServiceClient.PreviewInput", extra={ "serviceName": "google.cloud.video.livestream.v1.LivestreamService", - "rpcName": "StartChannel", + "rpcName": "PreviewInput", "httpRequest": http_request, "metadata": http_request["headers"], }, ) # Send the request - response = LivestreamServiceRestTransport._StartChannel._get_response( + response = LivestreamServiceRestTransport._PreviewInput._get_response( self._host, metadata, query_params, @@ -5823,19 +5988,21 @@ def __call__( raise core_exceptions.from_http_response(response) # Return the response - resp = operations_pb2.Operation() - json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = service.PreviewInputResponse() + pb_resp = service.PreviewInputResponse.pb(resp) - resp = self._interceptor.post_start_channel(resp) + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_preview_input(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_start_channel_with_metadata( + resp, _ = self._interceptor.post_preview_input_with_metadata( resp, response_metadata ) if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( logging.DEBUG ): # pragma: NO COVER try: - response_payload = json_format.MessageToJson(resp) + response_payload = service.PreviewInputResponse.to_json(response) except: response_payload = None http_response = { @@ -5844,21 +6011,21 @@ def __call__( "status": response.status_code, } _LOGGER.debug( - "Received response for google.cloud.video.livestream_v1.LivestreamServiceClient.start_channel", + "Received response for google.cloud.video.livestream_v1.LivestreamServiceClient.preview_input", extra={ "serviceName": "google.cloud.video.livestream.v1.LivestreamService", - "rpcName": "StartChannel", + "rpcName": "PreviewInput", "metadata": http_response["headers"], "httpResponse": http_response, }, ) return resp - class _StopChannel( - _BaseLivestreamServiceRestTransport._BaseStopChannel, LivestreamServiceRestStub + class _StartChannel( + _BaseLivestreamServiceRestTransport._BaseStartChannel, LivestreamServiceRestStub ): def __hash__(self): - return hash("LivestreamServiceRestTransport.StopChannel") + return hash("LivestreamServiceRestTransport.StartChannel") @staticmethod def _get_response( @@ -5885,18 +6052,18 @@ def _get_response( def __call__( self, - request: service.StopChannelRequest, + request: service.StartChannelRequest, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> operations_pb2.Operation: - r"""Call the stop channel method over HTTP. + r"""Call the start channel method over HTTP. Args: - request (~.service.StopChannelRequest): + request (~.service.StartChannelRequest): The request object. Request message for - "LivestreamService.StopChannel". + "LivestreamService.StartChannel". retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -5914,20 +6081,20 @@ def __call__( """ http_options = ( - _BaseLivestreamServiceRestTransport._BaseStopChannel._get_http_options() + _BaseLivestreamServiceRestTransport._BaseStartChannel._get_http_options() ) - request, metadata = self._interceptor.pre_stop_channel(request, metadata) - transcoded_request = _BaseLivestreamServiceRestTransport._BaseStopChannel._get_transcoded_request( + request, metadata = self._interceptor.pre_start_channel(request, metadata) + transcoded_request = _BaseLivestreamServiceRestTransport._BaseStartChannel._get_transcoded_request( http_options, request ) - body = _BaseLivestreamServiceRestTransport._BaseStopChannel._get_request_body_json( + body = _BaseLivestreamServiceRestTransport._BaseStartChannel._get_request_body_json( transcoded_request ) # Jsonify the query params - query_params = _BaseLivestreamServiceRestTransport._BaseStopChannel._get_query_params_json( + query_params = _BaseLivestreamServiceRestTransport._BaseStartChannel._get_query_params_json( transcoded_request ) @@ -5949,17 +6116,17 @@ def __call__( "headers": dict(metadata), } _LOGGER.debug( - f"Sending request for google.cloud.video.livestream_v1.LivestreamServiceClient.StopChannel", + f"Sending request for google.cloud.video.livestream_v1.LivestreamServiceClient.StartChannel", extra={ "serviceName": "google.cloud.video.livestream.v1.LivestreamService", - "rpcName": "StopChannel", + "rpcName": "StartChannel", "httpRequest": http_request, "metadata": http_request["headers"], }, ) # Send the request - response = LivestreamServiceRestTransport._StopChannel._get_response( + response = LivestreamServiceRestTransport._StartChannel._get_response( self._host, metadata, query_params, @@ -5978,9 +6145,9 @@ def __call__( resp = operations_pb2.Operation() json_format.Parse(response.content, resp, ignore_unknown_fields=True) - resp = self._interceptor.post_stop_channel(resp) + resp = self._interceptor.post_start_channel(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_stop_channel_with_metadata( + resp, _ = self._interceptor.post_start_channel_with_metadata( resp, response_metadata ) if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( @@ -5996,22 +6163,22 @@ def __call__( "status": response.status_code, } _LOGGER.debug( - "Received response for google.cloud.video.livestream_v1.LivestreamServiceClient.stop_channel", + "Received response for google.cloud.video.livestream_v1.LivestreamServiceClient.start_channel", extra={ "serviceName": "google.cloud.video.livestream.v1.LivestreamService", - "rpcName": "StopChannel", + "rpcName": "StartChannel", "metadata": http_response["headers"], "httpResponse": http_response, }, ) return resp - class _UpdateChannel( - _BaseLivestreamServiceRestTransport._BaseUpdateChannel, + class _StartDistribution( + _BaseLivestreamServiceRestTransport._BaseStartDistribution, LivestreamServiceRestStub, ): def __hash__(self): - return hash("LivestreamServiceRestTransport.UpdateChannel") + return hash("LivestreamServiceRestTransport.StartDistribution") @staticmethod def _get_response( @@ -6038,18 +6205,18 @@ def _get_response( def __call__( self, - request: service.UpdateChannelRequest, + request: service.StartDistributionRequest, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> operations_pb2.Operation: - r"""Call the update channel method over HTTP. + r"""Call the start distribution method over HTTP. Args: - request (~.service.UpdateChannelRequest): + request (~.service.StartDistributionRequest): The request object. Request message for - "LivestreamService.UpdateChannel". + "LivestreamService.StartDistribution". retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -6067,20 +6234,22 @@ def __call__( """ http_options = ( - _BaseLivestreamServiceRestTransport._BaseUpdateChannel._get_http_options() + _BaseLivestreamServiceRestTransport._BaseStartDistribution._get_http_options() ) - request, metadata = self._interceptor.pre_update_channel(request, metadata) - transcoded_request = _BaseLivestreamServiceRestTransport._BaseUpdateChannel._get_transcoded_request( + request, metadata = self._interceptor.pre_start_distribution( + request, metadata + ) + transcoded_request = _BaseLivestreamServiceRestTransport._BaseStartDistribution._get_transcoded_request( http_options, request ) - body = _BaseLivestreamServiceRestTransport._BaseUpdateChannel._get_request_body_json( + body = _BaseLivestreamServiceRestTransport._BaseStartDistribution._get_request_body_json( transcoded_request ) # Jsonify the query params - query_params = _BaseLivestreamServiceRestTransport._BaseUpdateChannel._get_query_params_json( + query_params = _BaseLivestreamServiceRestTransport._BaseStartDistribution._get_query_params_json( transcoded_request ) @@ -6102,17 +6271,17 @@ def __call__( "headers": dict(metadata), } _LOGGER.debug( - f"Sending request for google.cloud.video.livestream_v1.LivestreamServiceClient.UpdateChannel", + f"Sending request for google.cloud.video.livestream_v1.LivestreamServiceClient.StartDistribution", extra={ "serviceName": "google.cloud.video.livestream.v1.LivestreamService", - "rpcName": "UpdateChannel", + "rpcName": "StartDistribution", "httpRequest": http_request, "metadata": http_request["headers"], }, ) # Send the request - response = LivestreamServiceRestTransport._UpdateChannel._get_response( + response = LivestreamServiceRestTransport._StartDistribution._get_response( self._host, metadata, query_params, @@ -6131,9 +6300,9 @@ def __call__( resp = operations_pb2.Operation() json_format.Parse(response.content, resp, ignore_unknown_fields=True) - resp = self._interceptor.post_update_channel(resp) + resp = self._interceptor.post_start_distribution(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_update_channel_with_metadata( + resp, _ = self._interceptor.post_start_distribution_with_metadata( resp, response_metadata ) if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( @@ -6149,22 +6318,21 @@ def __call__( "status": response.status_code, } _LOGGER.debug( - "Received response for google.cloud.video.livestream_v1.LivestreamServiceClient.update_channel", + "Received response for google.cloud.video.livestream_v1.LivestreamServiceClient.start_distribution", extra={ "serviceName": "google.cloud.video.livestream.v1.LivestreamService", - "rpcName": "UpdateChannel", + "rpcName": "StartDistribution", "metadata": http_response["headers"], "httpResponse": http_response, }, ) return resp - class _UpdateDvrSession( - _BaseLivestreamServiceRestTransport._BaseUpdateDvrSession, - LivestreamServiceRestStub, + class _StopChannel( + _BaseLivestreamServiceRestTransport._BaseStopChannel, LivestreamServiceRestStub ): def __hash__(self): - return hash("LivestreamServiceRestTransport.UpdateDvrSession") + return hash("LivestreamServiceRestTransport.StopChannel") @staticmethod def _get_response( @@ -6191,18 +6359,18 @@ def _get_response( def __call__( self, - request: service.UpdateDvrSessionRequest, + request: service.StopChannelRequest, *, 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. + r"""Call the stop channel method over HTTP. Args: - request (~.service.UpdateDvrSessionRequest): + request (~.service.StopChannelRequest): The request object. Request message for - "LivestreamService.UpdateDvrSession". + "LivestreamService.StopChannel". retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -6220,22 +6388,20 @@ def __call__( """ http_options = ( - _BaseLivestreamServiceRestTransport._BaseUpdateDvrSession._get_http_options() + _BaseLivestreamServiceRestTransport._BaseStopChannel._get_http_options() ) - request, metadata = self._interceptor.pre_update_dvr_session( - request, metadata - ) - transcoded_request = _BaseLivestreamServiceRestTransport._BaseUpdateDvrSession._get_transcoded_request( + request, metadata = self._interceptor.pre_stop_channel(request, metadata) + transcoded_request = _BaseLivestreamServiceRestTransport._BaseStopChannel._get_transcoded_request( http_options, request ) - body = _BaseLivestreamServiceRestTransport._BaseUpdateDvrSession._get_request_body_json( + body = _BaseLivestreamServiceRestTransport._BaseStopChannel._get_request_body_json( transcoded_request ) # Jsonify the query params - query_params = _BaseLivestreamServiceRestTransport._BaseUpdateDvrSession._get_query_params_json( + query_params = _BaseLivestreamServiceRestTransport._BaseStopChannel._get_query_params_json( transcoded_request ) @@ -6257,17 +6423,17 @@ def __call__( "headers": dict(metadata), } _LOGGER.debug( - f"Sending request for google.cloud.video.livestream_v1.LivestreamServiceClient.UpdateDvrSession", + f"Sending request for google.cloud.video.livestream_v1.LivestreamServiceClient.StopChannel", extra={ "serviceName": "google.cloud.video.livestream.v1.LivestreamService", - "rpcName": "UpdateDvrSession", + "rpcName": "StopChannel", "httpRequest": http_request, "metadata": http_request["headers"], }, ) # Send the request - response = LivestreamServiceRestTransport._UpdateDvrSession._get_response( + response = LivestreamServiceRestTransport._StopChannel._get_response( self._host, metadata, query_params, @@ -6286,9 +6452,9 @@ def __call__( resp = operations_pb2.Operation() json_format.Parse(response.content, resp, ignore_unknown_fields=True) - resp = self._interceptor.post_update_dvr_session(resp) + resp = self._interceptor.post_stop_channel(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_update_dvr_session_with_metadata( + resp, _ = self._interceptor.post_stop_channel_with_metadata( resp, response_metadata ) if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( @@ -6304,21 +6470,22 @@ def __call__( "status": response.status_code, } _LOGGER.debug( - "Received response for google.cloud.video.livestream_v1.LivestreamServiceClient.update_dvr_session", + "Received response for google.cloud.video.livestream_v1.LivestreamServiceClient.stop_channel", extra={ "serviceName": "google.cloud.video.livestream.v1.LivestreamService", - "rpcName": "UpdateDvrSession", + "rpcName": "StopChannel", "metadata": http_response["headers"], "httpResponse": http_response, }, ) return resp - class _UpdateInput( - _BaseLivestreamServiceRestTransport._BaseUpdateInput, LivestreamServiceRestStub + class _StopDistribution( + _BaseLivestreamServiceRestTransport._BaseStopDistribution, + LivestreamServiceRestStub, ): def __hash__(self): - return hash("LivestreamServiceRestTransport.UpdateInput") + return hash("LivestreamServiceRestTransport.StopDistribution") @staticmethod def _get_response( @@ -6345,18 +6512,18 @@ def _get_response( def __call__( self, - request: service.UpdateInputRequest, + request: service.StopDistributionRequest, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> operations_pb2.Operation: - r"""Call the update input method over HTTP. + r"""Call the stop distribution method over HTTP. Args: - request (~.service.UpdateInputRequest): + request (~.service.StopDistributionRequest): The request object. Request message for - "LivestreamService.UpdateInput". + "LivestreamService.StopDistribution". retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -6374,20 +6541,22 @@ def __call__( """ http_options = ( - _BaseLivestreamServiceRestTransport._BaseUpdateInput._get_http_options() + _BaseLivestreamServiceRestTransport._BaseStopDistribution._get_http_options() ) - request, metadata = self._interceptor.pre_update_input(request, metadata) - transcoded_request = _BaseLivestreamServiceRestTransport._BaseUpdateInput._get_transcoded_request( + request, metadata = self._interceptor.pre_stop_distribution( + request, metadata + ) + transcoded_request = _BaseLivestreamServiceRestTransport._BaseStopDistribution._get_transcoded_request( http_options, request ) - body = _BaseLivestreamServiceRestTransport._BaseUpdateInput._get_request_body_json( + body = _BaseLivestreamServiceRestTransport._BaseStopDistribution._get_request_body_json( transcoded_request ) # Jsonify the query params - query_params = _BaseLivestreamServiceRestTransport._BaseUpdateInput._get_query_params_json( + query_params = _BaseLivestreamServiceRestTransport._BaseStopDistribution._get_query_params_json( transcoded_request ) @@ -6409,17 +6578,17 @@ def __call__( "headers": dict(metadata), } _LOGGER.debug( - f"Sending request for google.cloud.video.livestream_v1.LivestreamServiceClient.UpdateInput", + f"Sending request for google.cloud.video.livestream_v1.LivestreamServiceClient.StopDistribution", extra={ "serviceName": "google.cloud.video.livestream.v1.LivestreamService", - "rpcName": "UpdateInput", + "rpcName": "StopDistribution", "httpRequest": http_request, "metadata": http_request["headers"], }, ) # Send the request - response = LivestreamServiceRestTransport._UpdateInput._get_response( + response = LivestreamServiceRestTransport._StopDistribution._get_response( self._host, metadata, query_params, @@ -6438,7 +6607,467 @@ def __call__( resp = operations_pb2.Operation() json_format.Parse(response.content, resp, ignore_unknown_fields=True) - resp = self._interceptor.post_update_input(resp) + resp = self._interceptor.post_stop_distribution(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_stop_distribution_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.stop_distribution", + extra={ + "serviceName": "google.cloud.video.livestream.v1.LivestreamService", + "rpcName": "StopDistribution", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _UpdateChannel( + _BaseLivestreamServiceRestTransport._BaseUpdateChannel, + LivestreamServiceRestStub, + ): + def __hash__(self): + return hash("LivestreamServiceRestTransport.UpdateChannel") + + @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.UpdateChannelRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + r"""Call the update channel method over HTTP. + + Args: + request (~.service.UpdateChannelRequest): + The request object. Request message for + "LivestreamService.UpdateChannel". + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each 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._BaseUpdateChannel._get_http_options() + ) + + request, metadata = self._interceptor.pre_update_channel(request, metadata) + transcoded_request = _BaseLivestreamServiceRestTransport._BaseUpdateChannel._get_transcoded_request( + http_options, request + ) + + body = _BaseLivestreamServiceRestTransport._BaseUpdateChannel._get_request_body_json( + transcoded_request + ) + + # Jsonify the query params + query_params = _BaseLivestreamServiceRestTransport._BaseUpdateChannel._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.UpdateChannel", + extra={ + "serviceName": "google.cloud.video.livestream.v1.LivestreamService", + "rpcName": "UpdateChannel", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = LivestreamServiceRestTransport._UpdateChannel._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_channel(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_update_channel_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_channel", + extra={ + "serviceName": "google.cloud.video.livestream.v1.LivestreamService", + "rpcName": "UpdateChannel", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + 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 + ): + def __hash__(self): + return hash("LivestreamServiceRestTransport.UpdateInput") + + @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.UpdateInputRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + r"""Call the update input method over HTTP. + + Args: + request (~.service.UpdateInputRequest): + The request object. Request message for + "LivestreamService.UpdateInput". + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each 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._BaseUpdateInput._get_http_options() + ) + + request, metadata = self._interceptor.pre_update_input(request, metadata) + transcoded_request = _BaseLivestreamServiceRestTransport._BaseUpdateInput._get_transcoded_request( + http_options, request + ) + + body = _BaseLivestreamServiceRestTransport._BaseUpdateInput._get_request_body_json( + transcoded_request + ) + + # Jsonify the query params + query_params = _BaseLivestreamServiceRestTransport._BaseUpdateInput._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.UpdateInput", + extra={ + "serviceName": "google.cloud.video.livestream.v1.LivestreamService", + "rpcName": "UpdateInput", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = LivestreamServiceRestTransport._UpdateInput._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_input(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] resp, _ = self._interceptor.post_update_input_with_metadata( resp, response_metadata @@ -6802,6 +7431,14 @@ def list_inputs( # In C++ this would require a dynamic_cast return self._ListInputs(self._session, self._host, self._interceptor) # type: ignore + @property + def preview_input( + self, + ) -> Callable[[service.PreviewInputRequest], service.PreviewInputResponse]: + # 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._PreviewInput(self._session, self._host, self._interceptor) # type: ignore + @property def start_channel( self, @@ -6810,6 +7447,14 @@ def start_channel( # In C++ this would require a dynamic_cast return self._StartChannel(self._session, self._host, self._interceptor) # type: ignore + @property + def start_distribution( + self, + ) -> Callable[[service.StartDistributionRequest], 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._StartDistribution(self._session, self._host, self._interceptor) # type: ignore + @property def stop_channel( self, @@ -6818,6 +7463,14 @@ def stop_channel( # In C++ this would require a dynamic_cast return self._StopChannel(self._session, self._host, self._interceptor) # type: ignore + @property + def stop_distribution( + self, + ) -> Callable[[service.StopDistributionRequest], 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._StopDistribution(self._session, self._host, self._interceptor) # type: ignore + @property def update_channel( 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 50f977abd26b..7ab50c2c0369 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 @@ -1337,6 +1337,63 @@ def _get_query_params_json(transcoded_request): query_params["$alt"] = "json;enum-encoding=int" return query_params + class _BasePreviewInput: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1/{name=projects/*/locations/*/inputs/*}:preview", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = service.PreviewInputRequest.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._BasePreviewInput._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + class _BaseStartChannel: def __hash__(self): # pragma: NO COVER return NotImplementedError("__hash__ must be implemented.") @@ -1394,6 +1451,63 @@ def _get_query_params_json(transcoded_request): query_params["$alt"] = "json;enum-encoding=int" return query_params + class _BaseStartDistribution: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1/{name=projects/*/locations/*/channels/*}:startdistribution", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = service.StartDistributionRequest.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._BaseStartDistribution._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + class _BaseStopChannel: def __hash__(self): # pragma: NO COVER return NotImplementedError("__hash__ must be implemented.") @@ -1451,6 +1565,63 @@ def _get_query_params_json(transcoded_request): query_params["$alt"] = "json;enum-encoding=int" return query_params + class _BaseStopDistribution: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1/{name=projects/*/locations/*/channels/*}:stopdistribution", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = service.StopDistributionRequest.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._BaseStopDistribution._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + class _BaseUpdateChannel: 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 57bf42aac0ca..02923371b40f 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 @@ -15,12 +15,16 @@ # from .outputs import ( AudioStream, + Distribution, + DistributionStream, ElementaryStream, Manifest, MuxStream, PreprocessingConfig, + RtmpPushOutputEndpoint, SegmentSettings, SpriteSheet, + SrtPushOutputEndpoint, TextStream, TimecodeConfig, VideoStream, @@ -29,10 +33,12 @@ Asset, AudioFormat, AudioStreamProperty, + AutoTranscriptionConfig, Channel, Clip, DvrSession, Encryption, + EncryptionUpdate, Event, Input, InputAttachment, @@ -82,8 +88,12 @@ ListInputsRequest, ListInputsResponse, OperationMetadata, + PreviewInputRequest, + PreviewInputResponse, StartChannelRequest, + StartDistributionRequest, StopChannelRequest, + StopDistributionRequest, UpdateChannelRequest, UpdateDvrSessionRequest, UpdateInputRequest, @@ -92,22 +102,28 @@ __all__ = ( "AudioStream", + "Distribution", + "DistributionStream", "ElementaryStream", "Manifest", "MuxStream", "PreprocessingConfig", + "RtmpPushOutputEndpoint", "SegmentSettings", "SpriteSheet", + "SrtPushOutputEndpoint", "TextStream", "TimecodeConfig", "VideoStream", "Asset", "AudioFormat", "AudioStreamProperty", + "AutoTranscriptionConfig", "Channel", "Clip", "DvrSession", "Encryption", + "EncryptionUpdate", "Event", "Input", "InputAttachment", @@ -155,8 +171,12 @@ "ListInputsRequest", "ListInputsResponse", "OperationMetadata", + "PreviewInputRequest", + "PreviewInputResponse", "StartChannelRequest", + "StartDistributionRequest", "StopChannelRequest", + "StopDistributionRequest", "UpdateChannelRequest", "UpdateDvrSessionRequest", "UpdateInputRequest", diff --git a/packages/google-cloud-video-live-stream/google/cloud/video/live_stream_v1/types/outputs.py b/packages/google-cloud-video-live-stream/google/cloud/video/live_stream_v1/types/outputs.py index f8dfed71df64..39afda9bc894 100644 --- a/packages/google-cloud-video-live-stream/google/cloud/video/live_stream_v1/types/outputs.py +++ b/packages/google-cloud-video-live-stream/google/cloud/video/live_stream_v1/types/outputs.py @@ -18,6 +18,7 @@ from typing import MutableMapping, MutableSequence from google.protobuf import duration_pb2 # type: ignore +from google.rpc import status_pb2 # type: ignore from google.type import datetime_pb2 # type: ignore import proto # type: ignore @@ -27,6 +28,10 @@ "ElementaryStream", "MuxStream", "Manifest", + "DistributionStream", + "Distribution", + "SrtPushOutputEndpoint", + "RtmpPushOutputEndpoint", "SpriteSheet", "PreprocessingConfig", "VideoStream", @@ -257,6 +262,201 @@ class ManifestType(proto.Enum): ) +class DistributionStream(proto.Message): + r"""Multiplexing settings for output streams used in + [Distribution][google.cloud.video.livestream.v1.Distribution]. + + Attributes: + key (str): + Required. A unique key for this distribution + stream. The key must be 1-63 characters in + length. The key must begin and end with a letter + (regardless of case) or a number, but can + contain dashes or underscores in between. + container (str): + Required. The container format. + + Supported container formats: + + - ``ts``, must contain exactly one audio stream and up to + one video stream. + - ``flv``, must contain at most one audio stream and at most + one video stream. + elementary_streams (MutableSequence[str]): + Required. List of ``ElementaryStream`` + [key][google.cloud.video.livestream.v1.ElementaryStream.key]s + multiplexed in this stream. Must contain at least one audio + stream and up to one video stream. + """ + + key: str = proto.Field( + proto.STRING, + number=1, + ) + container: str = proto.Field( + proto.STRING, + number=2, + ) + elementary_streams: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=3, + ) + + +class Distribution(proto.Message): + r"""Distribution configuration. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + key (str): + Required. A unique key for this distribution. + The key must be 1-63 characters in length. The + key must begin and end with a letter (regardless + of case) or a number, but can contain dashes or + underscores in between. + distribution_stream (str): + Required. ``DistributionStream`` + [key][google.cloud.video.livestream.v1.DistributionStream.key]s + that should appear in this distribution output. + + - For SRT protocol, only ``ts`` distribution streams can be + specified. + - For RTMP protocol, only ``flv`` distribution streams can + be specified. + state (google.cloud.video.live_stream_v1.types.Distribution.State): + Output only. State of the distribution. + error (google.rpc.status_pb2.Status): + Output only. Only present when the ``state`` is ``ERROR``. + The reason for the error state of the distribution. + srt_push (google.cloud.video.live_stream_v1.types.SrtPushOutputEndpoint): + Output endpoint using SRT_PUSH. + + This field is a member of `oneof`_ ``endpoint``. + rtmp_push (google.cloud.video.live_stream_v1.types.RtmpPushOutputEndpoint): + Output endpoint using RTMP_PUSH. + + This field is a member of `oneof`_ ``endpoint``. + """ + + class State(proto.Enum): + r"""State of this distribution. + + Values: + STATE_UNSPECIFIED (0): + State is not specified. + ERROR (5): + Distribution has trouble to produce or + deliver the output. + NOT_READY (6): + Distribution is not ready to be started. + READY (7): + Distribution is ready to be started. + AWAITING_INPUT (8): + Distribution is already started and is + waiting for input. + DISTRIBUTING (9): + Distribution is already started and is + generating output. + """ + STATE_UNSPECIFIED = 0 + ERROR = 5 + NOT_READY = 6 + READY = 7 + AWAITING_INPUT = 8 + DISTRIBUTING = 9 + + key: str = proto.Field( + proto.STRING, + number=1, + ) + distribution_stream: str = proto.Field( + proto.STRING, + number=2, + ) + state: State = proto.Field( + proto.ENUM, + number=3, + enum=State, + ) + error: status_pb2.Status = proto.Field( + proto.MESSAGE, + number=4, + message=status_pb2.Status, + ) + srt_push: "SrtPushOutputEndpoint" = proto.Field( + proto.MESSAGE, + number=5, + oneof="endpoint", + message="SrtPushOutputEndpoint", + ) + rtmp_push: "RtmpPushOutputEndpoint" = proto.Field( + proto.MESSAGE, + number=6, + oneof="endpoint", + message="RtmpPushOutputEndpoint", + ) + + +class SrtPushOutputEndpoint(proto.Message): + r"""Configurations for an output endpoint using SRT_PUSH as the + streaming protocol. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + uri (str): + Required. The full URI of the remote SRT + server. + passphrase_secret_version (str): + The name of the Secret Version containing the SRT encryption + passphrase, which is stored in Google Secret Manager. It + should be in the format of + ``projects/{project}/secrets/{secret_id}/versions/{version_number}``. + + This field is a member of `oneof`_ ``passphrase_source``. + """ + + uri: str = proto.Field( + proto.STRING, + number=1, + ) + passphrase_secret_version: str = proto.Field( + proto.STRING, + number=2, + oneof="passphrase_source", + ) + + +class RtmpPushOutputEndpoint(proto.Message): + r"""Configurations for an output endpoint using RTMP_PUSH as the + streaming protocol. + + Attributes: + uri (str): + Required. The full URI of the remote RTMP server. For + example: ``rtmp://192.168.123.321/live/my-stream`` or + ``rtmp://somedomain.com/someapp``. + stream_key (str): + Required. Stream key for RTMP protocol. + """ + + uri: str = proto.Field( + proto.STRING, + number=1, + ) + stream_key: str = proto.Field( + proto.STRING, + number=2, + ) + + class SpriteSheet(proto.Message): r"""Sprite sheet configuration. @@ -466,12 +666,21 @@ class Pad(proto.Message): class VideoStream(proto.Message): r"""Video stream resource. + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields Attributes: h264 (google.cloud.video.live_stream_v1.types.VideoStream.H264CodecSettings): H264 codec settings. + This field is a member of `oneof`_ ``codec_settings``. + h265 (google.cloud.video.live_stream_v1.types.VideoStream.H265CodecSettings): + H265 codec settings. + This field is a member of `oneof`_ ``codec_settings``. """ @@ -488,10 +697,10 @@ class H264CodecSettings(proto.Message): Attributes: width_pixels (int): Required. The width of the video in pixels. Must be an even - integer. Valid range is [320, 1920]. + integer. Valid range is [320, 4096]. height_pixels (int): Required. The height of the video in pixels. Must be an even - integer. Valid range is [180, 1080]. + integer. Valid range is [180, 2160]. frame_rate (float): Required. The target video frame rate in frames per second (FPS). Must be less than or equal to 60. Will default to the @@ -509,6 +718,8 @@ class H264CodecSettings(proto.Message): 3,000,000 (3 Mbps). - For HD resolution (<= 1080p), must be <= 15,000,000 (15 Mbps). + - For UHD resolution (<= 2160p), must be <= + 25,000,000 (25 Mbps). allow_open_gop (bool): Specifies whether an open Group of Pictures (GOP) structure should be allowed or not. The default is ``false``. @@ -652,12 +863,158 @@ class H264CodecSettings(proto.Message): number=16, ) + class H265CodecSettings(proto.Message): + r"""H265 codec settings. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + width_pixels (int): + Optional. The width of the video in pixels. Must be an even + integer. When not specified, the width is adjusted to match + the specified height and input aspect ratio. If both are + omitted, the input width is used. Valid range is [320, + 4096]. + height_pixels (int): + Optional. The height of the video in pixels. Must be an even + integer. When not specified, the height is adjusted to match + the specified width and input aspect ratio. If both are + omitted, the input height is used. Valid range is [180, + 2160]. + frame_rate (float): + Required. The target video frame rate in frames per second + (FPS). Must be less than or equal to 120. Will default to + the input frame rate if larger than the input frame rate. + The API will generate an output FPS that is divisible by the + input FPS, and smaller or equal to the target FPS. See + `Calculating frame + rate `__ + for more information. + bitrate_bps (int): + Required. The video bitrate in bits per + second. Minimum value is 10,000. + + - For SD resolution (< 720p), must be <= + 3,000,000 (3 Mbps). + - For HD resolution (<= 1080p), must be <= + 15,000,000 (15 Mbps). + - For UHD resolution (<= 2160p), must be <= + 25,000,000 (25 Mbps). + gop_frame_count (int): + Optional. Select the GOP size based on the specified frame + count. If GOP frame count is set instead of GOP duration, + GOP duration will be calculated by + ``gopFrameCount``/``frameRate``. The calculated GOP duration + must satisfy the limitations on ``gopDuration`` as well. + Valid range is [60, 600]. + + This field is a member of `oneof`_ ``gop_mode``. + gop_duration (google.protobuf.duration_pb2.Duration): + Optional. Select the GOP size based on the specified + duration. The default is ``2s``. Note that ``gopDuration`` + must be less than or equal to + [segment_duration][google.cloud.video.livestream.v1.SegmentSettings.segment_duration], + and + [segment_duration][google.cloud.video.livestream.v1.SegmentSettings.segment_duration] + must be divisible by ``gopDuration``. Valid range is [2s, + 20s]. + + All video streams in the same channel must have the same GOP + size. + + This field is a member of `oneof`_ ``gop_mode``. + vbv_size_bits (int): + Optional. Size of the Video Buffering Verifier (VBV) buffer + in bits. Must be greater than zero. The default is equal to + [bitrate_bps][google.cloud.video.livestream.v1.VideoStream.H265CodecSettings.bitrate_bps]. + vbv_fullness_bits (int): + Optional. Initial fullness of the Video Buffering Verifier + (VBV) buffer in bits. Must be greater than zero. The default + is equal to 90% of + [vbv_size_bits][google.cloud.video.livestream.v1.VideoStream.H265CodecSettings.vbv_size_bits]. + b_pyramid (bool): + Optional. Allow B-pyramid for reference frame selection. + This may not be supported on all decoders. The default is + ``false``. + b_frame_count (int): + Optional. The number of consecutive B-frames. Must be + greater than or equal to zero. Must be less than + [gop_frame_count][google.cloud.video.livestream.v1.VideoStream.H265CodecSettings.gop_frame_count] + if set. The default is 0. + aq_strength (float): + Optional. Specify the intensity of the + adaptive quantizer (AQ). Must be between 0 and + 1, where 0 disables the quantizer and 1 + maximizes the quantizer. A higher value equals a + lower bitrate but smoother image. The default is + 0. + """ + + width_pixels: int = proto.Field( + proto.INT32, + number=1, + ) + height_pixels: int = proto.Field( + proto.INT32, + number=2, + ) + frame_rate: float = proto.Field( + proto.DOUBLE, + number=3, + ) + bitrate_bps: int = proto.Field( + proto.INT32, + number=4, + ) + gop_frame_count: int = proto.Field( + proto.INT32, + number=7, + oneof="gop_mode", + ) + gop_duration: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=8, + oneof="gop_mode", + message=duration_pb2.Duration, + ) + vbv_size_bits: int = proto.Field( + proto.INT32, + number=9, + ) + vbv_fullness_bits: int = proto.Field( + proto.INT32, + number=10, + ) + b_pyramid: bool = proto.Field( + proto.BOOL, + number=11, + ) + b_frame_count: int = proto.Field( + proto.INT32, + number=12, + ) + aq_strength: float = proto.Field( + proto.DOUBLE, + number=13, + ) + h264: H264CodecSettings = proto.Field( proto.MESSAGE, number=20, oneof="codec_settings", message=H264CodecSettings, ) + h265: H265CodecSettings = proto.Field( + proto.MESSAGE, + number=21, + oneof="codec_settings", + message=H265CodecSettings, + ) class AudioStream(proto.Message): @@ -796,12 +1153,96 @@ class TextStream(proto.Message): - ``cea608`` - ``cea708`` + - ``webvtt`` + language_code (str): + Optional. The BCP-47 language code, such as ``en-US`` or + ``sr-Latn``. For more information, see + https://www.unicode.org/reports/tr35/#Unicode_locale_identifier. + display_name (str): + Optional. The name for this particular text + stream that will be added to the HLS/DASH + manifest. + output_cea_channel (str): + Optional. The channel of the closed caption in the output + stream. This field should only be set when textstream is + used for partner distribution. Must be one of ``CC1``, + ``CC2``, ``CC3``, and ``CC4``, if the + [codec][google.cloud.video.livestream.v1.TextStream.codec] + is ``cea608``; Must be one between ``SERVICE1`` and + ``SERVICE63``, if the + [codec][google.cloud.video.livestream.v1.TextStream.codec] + is ``cea708``. + mapping_ (MutableSequence[google.cloud.video.live_stream_v1.types.TextStream.TextMapping]): + Optional. The mapping for the input streams + and text tracks. """ + class TextMapping(proto.Message): + r"""The mapping for the input streams and text tracks. + + Attributes: + input_key (str): + Optional. The ``Channel`` + [InputAttachment.key][google.cloud.video.livestream.v1.InputAttachment.key] + that identifies the input that this text mapping applies to. + input_track (int): + Optional. The zero-based index of the track + in the input stream. + input_cea_channel (str): + Optional. The channel of the closed caption in the input + stream. If this field is set, the output + [codec][google.cloud.video.livestream.v1.TextStream.codec] + must be ``webvtt``. Must be one of ``CC1``, ``CC2``, + ``CC3``, and ``CC4``, if the codec of the input closed + caption is ``cea608``; Must be one between ``SERVICE1`` and + ``SERVICE64``, if the codec of the input closed caption is + ``cea708``. + from_language_code (str): + Optional. The BCP-47 source language code, such as ``en-US`` + or ``sr-Latn``. If differ from the textStream's language + code, enable translation. For more information on BCP-47 + language codes, see + https://www.unicode.org/reports/tr35/#Unicode_locale_identifier. + """ + + input_key: str = proto.Field( + proto.STRING, + number=4, + ) + input_track: int = proto.Field( + proto.INT32, + number=2, + ) + input_cea_channel: str = proto.Field( + proto.STRING, + number=5, + ) + from_language_code: str = proto.Field( + proto.STRING, + number=6, + ) + codec: str = proto.Field( proto.STRING, number=1, ) + language_code: str = proto.Field( + proto.STRING, + number=2, + ) + display_name: str = proto.Field( + proto.STRING, + number=4, + ) + output_cea_channel: str = proto.Field( + proto.STRING, + number=5, + ) + mapping_: MutableSequence[TextMapping] = proto.RepeatedField( + proto.MESSAGE, + number=3, + message=TextMapping, + ) class SegmentSettings(proto.Message): 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 9ae7daac4ebf..24f6ec51c039 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 @@ -41,12 +41,14 @@ "AudioStreamProperty", "AudioFormat", "InputAttachment", + "AutoTranscriptionConfig", "Event", "Clip", "TimeInterval", "DvrSession", "Asset", "Encryption", + "EncryptionUpdate", "Pool", }, ) @@ -121,12 +123,25 @@ class Tier(proto.Enum): Resolution <= 1920x1080. Bitrate <= 25 Mbps. FPS <= 60. UHD (3): - Resolution <= 4096x2160. Not supported yet. + Resolution <= 4096x2160. Bitrate <= 50 Mbps. + FPS <= 60. + SD_H265 (4): + Resolution <= 1280x720. Bitrate <= 6 Mbps. + FPS <= 60. H265 codec. + HD_H265 (5): + Resolution <= 1920x1080. Bitrate <= 25 Mbps. + FPS <= 60. H265 codec. + UHD_H265 (6): + Resolution <= 4096x2160. Bitrate <= 50 Mbps. + FPS <= 60. H265 codec. """ TIER_UNSPECIFIED = 0 SD = 1 HD = 2 UHD = 3 + SD_H265 = 4 + HD_H265 = 5 + UHD_H265 = 6 class SecurityRule(proto.Message): r"""Security rules for access control. Each field represents one @@ -236,6 +251,11 @@ class Channel(proto.Message): streams. manifests (MutableSequence[google.cloud.video.live_stream_v1.types.Manifest]): List of output manifests. + distribution_streams (MutableSequence[google.cloud.video.live_stream_v1.types.DistributionStream]): + Optional. List of multiplexing settings of + streams for distributions. + distributions (MutableSequence[google.cloud.video.live_stream_v1.types.Distribution]): + Optional. List of distributions. sprite_sheets (MutableSequence[google.cloud.video.live_stream_v1.types.SpriteSheet]): List of output sprite sheets. streaming_state (google.cloud.video.live_stream_v1.types.Channel.StreamingState): @@ -253,9 +273,9 @@ class Channel(proto.Message): timecode_config (google.cloud.video.live_stream_v1.types.TimecodeConfig): Configuration of timecode for this channel. encryptions (MutableSequence[google.cloud.video.live_stream_v1.types.Encryption]): - Encryption configurations for this channel. - Each configuration has an ID which is referred - to by each MuxStream to indicate which + Optional. Encryption configurations for this + channel. Each configuration has an ID which is + referred to by each MuxStream to indicate which configuration is used for that output. input_config (google.cloud.video.live_stream_v1.types.InputConfig): The configuration for input sources defined in @@ -267,6 +287,9 @@ class Channel(proto.Message): Optional. List of static overlay images. Those images display over the output content for the whole duration of the live stream. + auto_transcription_config (google.cloud.video.live_stream_v1.types.AutoTranscriptionConfig): + Optional. Advanced configurations for + auto-generated text streams. """ class StreamingState(proto.Enum): @@ -370,6 +393,18 @@ class Output(proto.Message): number=12, message=outputs.Manifest, ) + distribution_streams: MutableSequence[ + outputs.DistributionStream + ] = proto.RepeatedField( + proto.MESSAGE, + number=28, + message=outputs.DistributionStream, + ) + distributions: MutableSequence[outputs.Distribution] = proto.RepeatedField( + proto.MESSAGE, + number=29, + message=outputs.Distribution, + ) sprite_sheets: MutableSequence[outputs.SpriteSheet] = proto.RepeatedField( proto.MESSAGE, number=13, @@ -415,6 +450,11 @@ class Output(proto.Message): number=27, message="StaticOverlay", ) + auto_transcription_config: "AutoTranscriptionConfig" = proto.Field( + proto.MESSAGE, + number=30, + message="AutoTranscriptionConfig", + ) class NormalizedCoordinate(proto.Message): @@ -815,6 +855,76 @@ class AutomaticFailover(proto.Message): ) +class AutoTranscriptionConfig(proto.Message): + r"""Advanced configurations for auto-generated text streams. + + Attributes: + display_timing (google.cloud.video.live_stream_v1.types.AutoTranscriptionConfig.DisplayTiming): + Optional. Whether auto-generated text streams + are displayed synchronously or asynchronously + with the original audio. + quality_preset (google.cloud.video.live_stream_v1.types.AutoTranscriptionConfig.QualityPreset): + Optional. Tunes the latency and quality of + auto-generated captions. + """ + + class DisplayTiming(proto.Enum): + r"""Whether auto-generated text streams are displayed + synchronously or asynchronously with the original audio. + + Values: + DISPLAY_TIMING_UNSPECIFIED (0): + Display timing is not specified. Caption + display will be asynchronous by default. + ASYNC (1): + Caption will be displayed asynchronous with + audio. + SYNC (2): + Caption will be displayed synchronous with + audio. This option increases overall media + output latency, and reduces viewing latency + between audio and auto-generated captions. + """ + DISPLAY_TIMING_UNSPECIFIED = 0 + ASYNC = 1 + SYNC = 2 + + class QualityPreset(proto.Enum): + r"""Presets to tune the latency and quality of auto-generated + captions. + + Values: + QUALITY_PRESET_UNSPECIFIED (0): + Quality Preset is not specified. By default, + BALANCED_QUALITY will be used. + LOW_LATENCY (1): + Reduce the latency of auto-generated + captions. This may reduce the quality of the + captions. + BALANCED_QUALITY (2): + Default behavior when QualityPreset is not + specified. + IMPROVED_QUALITY (3): + Increases the quality of the auto-generated + captions at the cost of higher latency. + """ + QUALITY_PRESET_UNSPECIFIED = 0 + LOW_LATENCY = 1 + BALANCED_QUALITY = 2 + IMPROVED_QUALITY = 3 + + display_timing: DisplayTiming = proto.Field( + proto.ENUM, + number=1, + enum=DisplayTiming, + ) + quality_preset: QualityPreset = proto.Field( + proto.ENUM, + number=2, + enum=QualityPreset, + ) + + class Event(proto.Message): r"""Event is a sub-resource of a channel, which can be scheduled by the user to execute operations on a channel resource without @@ -860,6 +970,10 @@ class Event(proto.Message): unmute (google.cloud.video.live_stream_v1.types.Event.UnmuteTask): Unmutes the stream. + This field is a member of `oneof`_ ``task``. + update_encryptions (google.cloud.video.live_stream_v1.types.Event.UpdateEncryptionsTask): + Updates encryption settings. + This field is a member of `oneof`_ ``task``. execute_now (bool): When this field is set to true, the event will be executed @@ -997,6 +1111,22 @@ class UnmuteTask(proto.Message): """ + class UpdateEncryptionsTask(proto.Message): + r"""Update encryption settings. + + Attributes: + encryptions (MutableSequence[google.cloud.video.live_stream_v1.types.EncryptionUpdate]): + Required. A list of + [EncryptionUpdate][google.cloud.video.livestream.v1.EncryptionUpdate]s + that updates the existing encryption settings. + """ + + encryptions: MutableSequence["EncryptionUpdate"] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message="EncryptionUpdate", + ) + name: str = proto.Field( proto.STRING, number=1, @@ -1052,6 +1182,12 @@ class UnmuteTask(proto.Message): oneof="task", message=UnmuteTask, ) + update_encryptions: UpdateEncryptionsTask = proto.Field( + proto.MESSAGE, + number=17, + oneof="task", + message=UpdateEncryptionsTask, + ) execute_now: bool = proto.Field( proto.BOOL, number=9, @@ -1720,13 +1856,13 @@ class DrmSystems(proto.Message): Attributes: widevine (google.cloud.video.live_stream_v1.types.Encryption.Widevine): - Widevine configuration. + Optional. Widevine configuration. fairplay (google.cloud.video.live_stream_v1.types.Encryption.Fairplay): - Fairplay configuration. + Optional. Fairplay configuration. playready (google.cloud.video.live_stream_v1.types.Encryption.Playready): - Playready configuration. + Optional. Playready configuration. clearkey (google.cloud.video.live_stream_v1.types.Encryption.Clearkey): - Clearkey configuration. + Optional. Clearkey configuration. """ widevine: "Encryption.Widevine" = proto.Field( @@ -1807,6 +1943,33 @@ class MpegCommonEncryption(proto.Message): ) +class EncryptionUpdate(proto.Message): + r"""Encryption setting when updating encryption. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + id (str): + Required. Identifier for the encryption + option to be updated. + secret_manager_key_source (google.cloud.video.live_stream_v1.types.Encryption.SecretManagerSource): + For keys stored in Google Secret Manager. + + This field is a member of `oneof`_ ``secret_source``. + """ + + id: str = proto.Field( + proto.STRING, + number=1, + ) + secret_manager_key_source: "Encryption.SecretManagerSource" = proto.Field( + proto.MESSAGE, + number=2, + oneof="secret_source", + message="Encryption.SecretManagerSource", + ) + + class Pool(proto.Message): r"""Pool resource defines the configuration of Live Stream pools for a specific location. Currently we support only one pool 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 b8c2e6b9cb42..cc6b5f5df893 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 @@ -39,6 +39,8 @@ "UpdateChannelRequest", "StartChannelRequest", "StopChannelRequest", + "StartDistributionRequest", + "StopDistributionRequest", "CreateInputRequest", "ListInputsRequest", "ListInputsResponse", @@ -65,6 +67,8 @@ "OperationMetadata", "GetPoolRequest", "UpdatePoolRequest", + "PreviewInputRequest", + "PreviewInputResponse", }, ) @@ -79,9 +83,13 @@ class CreateAssetRequest(proto.Message): asset (google.cloud.video.live_stream_v1.types.Asset): Required. The asset resource to be created. asset_id (str): - Required. The ID of the asset resource to be created. This - value must be 1-63 characters, begin and end with - ``[a-z0-9]``, could contain dashes (-) in between. + Required. The ID of the asset resource to be created. + + This value must be 1-63 characters, begin and end with a + lower-case letter or a number, and consist of only + lower-case letters, numbers, and hyphens. In other words, it + must match the following regex: + ``^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$``. request_id (str): A request ID to identify requests. Specify a unique request ID so that if you must retry your request, the server will @@ -255,9 +263,13 @@ class CreateChannelRequest(proto.Message): channel (google.cloud.video.live_stream_v1.types.Channel): Required. The channel resource to be created. channel_id (str): - Required. The ID of the channel resource to be created. This - value must be 1-63 characters, begin and end with - ``[a-z0-9]``, could contain dashes (-) in between. + Required. The ID of the channel resource to be created. + + This value must be 1-63 characters, begin and end with a + lower-case letter or a number, and consist of only + lower-case letters, numbers, and hyphens. In other words, it + must match the following regex: + ``^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$``. request_id (str): A request ID to identify requests. Specify a unique request ID so that if you must retry your request, the server will @@ -573,6 +585,96 @@ class StopChannelRequest(proto.Message): ) +class StartDistributionRequest(proto.Message): + r"""Request message for "LivestreamService.StartDistribution". + + Attributes: + name (str): + Required. The name of the channel resource, in the form of: + ``projects/{project}/locations/{location}/channels/{channelId}``. + distribution_keys (MutableSequence[str]): + Optional. A list of keys to identify the + distribution configuration in the channel + resource. If left empty, all the distributions + in the channel specification will be started. + 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, + ) + distribution_keys: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=2, + ) + request_id: str = proto.Field( + proto.STRING, + number=3, + ) + + +class StopDistributionRequest(proto.Message): + r"""Request message for "LivestreamService.StopDistribution". + + Attributes: + name (str): + Required. The name of the channel resource, in the form of: + ``projects/{project}/locations/{location}/channels/{channelId}``. + distribution_keys (MutableSequence[str]): + Optional. A list of key to identify the + distribution configuration in the channel + resource. If left empty, all the distributions + in the channel specification will be stopped. + 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, + ) + distribution_keys: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=2, + ) + request_id: str = proto.Field( + proto.STRING, + number=3, + ) + + class CreateInputRequest(proto.Message): r"""Request message for "LivestreamService.CreateInput". @@ -583,9 +685,13 @@ class CreateInputRequest(proto.Message): input (google.cloud.video.live_stream_v1.types.Input): Required. The input resource to be created. input_id (str): - Required. The ID of the input resource to be created. This - value must be 1-63 characters, begin and end with - ``[a-z0-9]``, could contain dashes (-) in between. + Required. The ID of the input resource to be created. + + This value must be 1-63 characters, begin and end with a + lower-case letter or a number, and consist of only + lower-case letters, numbers, and hyphens. In other words, it + must match the following regex: + ``^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$``. request_id (str): A request ID to identify requests. Specify a unique request ID so that if you must retry your request, the server will @@ -824,9 +930,13 @@ class CreateEventRequest(proto.Message): event (google.cloud.video.live_stream_v1.types.Event): Required. The event resource to be created. event_id (str): - Required. The ID of the event resource to be created. This - value must be 1-63 characters, begin and end with - ``[a-z0-9]``, could contain dashes (-) in between. + Required. The ID of the event resource to be created. + + This value must be 1-63 characters, begin and end with a + lower-case letter or a number, and consist of only + lower-case letters, numbers, and hyphens. In other words, it + must match the following regex: + ``^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$``. request_id (str): A request ID to identify requests. Specify a unique request ID so that if you must retry your request, the server will @@ -1099,12 +1209,13 @@ class CreateClipRequest(proto.Message): Required. The parent resource name, in the following form: ``projects/{project}/locations/{location}/channels/{channel}``. clip_id (str): - Required. Id of the requesting object in the - following form: + Required. The ID of the clip resource to be created. - 1. 1 character minimum, 63 characters maximum - 2. Only contains letters, digits, underscores, - and hyphens + This value must be 1-63 characters, begin and end with a + lower-case letter or a number, and consist of only + lower-case letters, numbers, and hyphens. In other words, it + must match the following regex: + ``^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$``. clip (google.cloud.video.live_stream_v1.types.Clip): Required. The resource being created request_id (str): @@ -1282,12 +1393,13 @@ class CreateDvrSessionRequest(proto.Message): 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: + Required. The ID of the DVR session resource to be created. - 1. 1 character minimum, 63 characters maximum - 2. Only contains letters, digits, underscores, - and hyphens + This value must be 1-63 characters, begin and end with a + lower-case letter or a number, and consist of only + lower-case letters, numbers, and hyphens. In other words, it + must match the following regex: + ``^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$``. dvr_session (google.cloud.video.live_stream_v1.types.DvrSession): Required. The resource being created request_id (str): @@ -1542,4 +1654,43 @@ class UpdatePoolRequest(proto.Message): ) +class PreviewInputRequest(proto.Message): + r"""Request message for "LivestreamService.PreviewInput". + + Attributes: + name (str): + Required. The name of the input resource, in the form of: + ``projects/{project}/locations/{location}/inputs/{inputId}``. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class PreviewInputResponse(proto.Message): + r"""Response message for "LivestreamService.PreviewInput". + + Attributes: + uri (str): + URI to display the preview content. + bearer_token (str): + A bearer token used to authenticate + connections that display the preview content. + The token expires after one hour. For HTTP + connections, this token should be included as a + bearer token inside the Authorization header. + """ + + uri: str = proto.Field( + proto.STRING, + number=1, + ) + bearer_token: str = proto.Field( + proto.STRING, + number=2, + ) + + __all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-cloud-video-live-stream/samples/generated_samples/livestream_v1_generated_livestream_service_preview_input_async.py b/packages/google-cloud-video-live-stream/samples/generated_samples/livestream_v1_generated_livestream_service_preview_input_async.py new file mode 100644 index 000000000000..c5066d8d026d --- /dev/null +++ b/packages/google-cloud-video-live-stream/samples/generated_samples/livestream_v1_generated_livestream_service_preview_input_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 PreviewInput +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It 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_PreviewInput_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_preview_input(): + # Create a client + client = live_stream_v1.LivestreamServiceAsyncClient() + + # Initialize request argument(s) + request = live_stream_v1.PreviewInputRequest( + name="name_value", + ) + + # Make the request + response = await client.preview_input(request=request) + + # Handle the response + print(response) + +# [END livestream_v1_generated_LivestreamService_PreviewInput_async] diff --git a/packages/google-cloud-video-live-stream/samples/generated_samples/livestream_v1_generated_livestream_service_preview_input_sync.py b/packages/google-cloud-video-live-stream/samples/generated_samples/livestream_v1_generated_livestream_service_preview_input_sync.py new file mode 100644 index 000000000000..2f9bef4717ec --- /dev/null +++ b/packages/google-cloud-video-live-stream/samples/generated_samples/livestream_v1_generated_livestream_service_preview_input_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 PreviewInput +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It 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_PreviewInput_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_preview_input(): + # Create a client + client = live_stream_v1.LivestreamServiceClient() + + # Initialize request argument(s) + request = live_stream_v1.PreviewInputRequest( + name="name_value", + ) + + # Make the request + response = client.preview_input(request=request) + + # Handle the response + print(response) + +# [END livestream_v1_generated_LivestreamService_PreviewInput_sync] diff --git a/packages/google-cloud-video-live-stream/samples/generated_samples/livestream_v1_generated_livestream_service_start_distribution_async.py b/packages/google-cloud-video-live-stream/samples/generated_samples/livestream_v1_generated_livestream_service_start_distribution_async.py new file mode 100644 index 000000000000..7970d34d1dbb --- /dev/null +++ b/packages/google-cloud-video-live-stream/samples/generated_samples/livestream_v1_generated_livestream_service_start_distribution_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 StartDistribution +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It 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_StartDistribution_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_start_distribution(): + # Create a client + client = live_stream_v1.LivestreamServiceAsyncClient() + + # Initialize request argument(s) + request = live_stream_v1.StartDistributionRequest( + name="name_value", + ) + + # Make the request + operation = client.start_distribution(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END livestream_v1_generated_LivestreamService_StartDistribution_async] diff --git a/packages/google-cloud-video-live-stream/samples/generated_samples/livestream_v1_generated_livestream_service_start_distribution_sync.py b/packages/google-cloud-video-live-stream/samples/generated_samples/livestream_v1_generated_livestream_service_start_distribution_sync.py new file mode 100644 index 000000000000..16b5b072d5a4 --- /dev/null +++ b/packages/google-cloud-video-live-stream/samples/generated_samples/livestream_v1_generated_livestream_service_start_distribution_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 StartDistribution +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It 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_StartDistribution_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_start_distribution(): + # Create a client + client = live_stream_v1.LivestreamServiceClient() + + # Initialize request argument(s) + request = live_stream_v1.StartDistributionRequest( + name="name_value", + ) + + # Make the request + operation = client.start_distribution(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END livestream_v1_generated_LivestreamService_StartDistribution_sync] diff --git a/packages/google-cloud-video-live-stream/samples/generated_samples/livestream_v1_generated_livestream_service_stop_distribution_async.py b/packages/google-cloud-video-live-stream/samples/generated_samples/livestream_v1_generated_livestream_service_stop_distribution_async.py new file mode 100644 index 000000000000..9349025f014c --- /dev/null +++ b/packages/google-cloud-video-live-stream/samples/generated_samples/livestream_v1_generated_livestream_service_stop_distribution_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 StopDistribution +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It 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_StopDistribution_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_stop_distribution(): + # Create a client + client = live_stream_v1.LivestreamServiceAsyncClient() + + # Initialize request argument(s) + request = live_stream_v1.StopDistributionRequest( + name="name_value", + ) + + # Make the request + operation = client.stop_distribution(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END livestream_v1_generated_LivestreamService_StopDistribution_async] diff --git a/packages/google-cloud-video-live-stream/samples/generated_samples/livestream_v1_generated_livestream_service_stop_distribution_sync.py b/packages/google-cloud-video-live-stream/samples/generated_samples/livestream_v1_generated_livestream_service_stop_distribution_sync.py new file mode 100644 index 000000000000..6da7b4f9e5a0 --- /dev/null +++ b/packages/google-cloud-video-live-stream/samples/generated_samples/livestream_v1_generated_livestream_service_stop_distribution_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 StopDistribution +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It 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_StopDistribution_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_stop_distribution(): + # Create a client + client = live_stream_v1.LivestreamServiceClient() + + # Initialize request argument(s) + request = live_stream_v1.StopDistributionRequest( + name="name_value", + ) + + # Make the request + operation = client.stop_distribution(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END livestream_v1_generated_LivestreamService_StopDistribution_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 158b160f6b4e..d5c33aa3cecb 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 @@ -4126,6 +4126,167 @@ ], "title": "livestream_v1_generated_livestream_service_list_inputs_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.preview_input", + "method": { + "fullName": "google.cloud.video.livestream.v1.LivestreamService.PreviewInput", + "service": { + "fullName": "google.cloud.video.livestream.v1.LivestreamService", + "shortName": "LivestreamService" + }, + "shortName": "PreviewInput" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.video.live_stream_v1.types.PreviewInputRequest" + }, + { + "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.PreviewInputResponse", + "shortName": "preview_input" + }, + "description": "Sample for PreviewInput", + "file": "livestream_v1_generated_livestream_service_preview_input_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "livestream_v1_generated_LivestreamService_PreviewInput_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_preview_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.preview_input", + "method": { + "fullName": "google.cloud.video.livestream.v1.LivestreamService.PreviewInput", + "service": { + "fullName": "google.cloud.video.livestream.v1.LivestreamService", + "shortName": "LivestreamService" + }, + "shortName": "PreviewInput" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.video.live_stream_v1.types.PreviewInputRequest" + }, + { + "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.PreviewInputResponse", + "shortName": "preview_input" + }, + "description": "Sample for PreviewInput", + "file": "livestream_v1_generated_livestream_service_preview_input_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "livestream_v1_generated_LivestreamService_PreviewInput_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_preview_input_sync.py" + }, { "canonical": true, "clientMethod": { @@ -4287,6 +4448,175 @@ ], "title": "livestream_v1_generated_livestream_service_start_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.start_distribution", + "method": { + "fullName": "google.cloud.video.livestream.v1.LivestreamService.StartDistribution", + "service": { + "fullName": "google.cloud.video.livestream.v1.LivestreamService", + "shortName": "LivestreamService" + }, + "shortName": "StartDistribution" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.video.live_stream_v1.types.StartDistributionRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "distribution_keys", + "type": "MutableSequence[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": "start_distribution" + }, + "description": "Sample for StartDistribution", + "file": "livestream_v1_generated_livestream_service_start_distribution_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "livestream_v1_generated_LivestreamService_StartDistribution_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_start_distribution_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.video.live_stream_v1.LivestreamServiceClient", + "shortName": "LivestreamServiceClient" + }, + "fullName": "google.cloud.video.live_stream_v1.LivestreamServiceClient.start_distribution", + "method": { + "fullName": "google.cloud.video.livestream.v1.LivestreamService.StartDistribution", + "service": { + "fullName": "google.cloud.video.livestream.v1.LivestreamService", + "shortName": "LivestreamService" + }, + "shortName": "StartDistribution" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.video.live_stream_v1.types.StartDistributionRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "distribution_keys", + "type": "MutableSequence[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": "start_distribution" + }, + "description": "Sample for StartDistribution", + "file": "livestream_v1_generated_livestream_service_start_distribution_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "livestream_v1_generated_LivestreamService_StartDistribution_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_start_distribution_sync.py" + }, { "canonical": true, "clientMethod": { @@ -4448,6 +4778,175 @@ ], "title": "livestream_v1_generated_livestream_service_stop_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.stop_distribution", + "method": { + "fullName": "google.cloud.video.livestream.v1.LivestreamService.StopDistribution", + "service": { + "fullName": "google.cloud.video.livestream.v1.LivestreamService", + "shortName": "LivestreamService" + }, + "shortName": "StopDistribution" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.video.live_stream_v1.types.StopDistributionRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "distribution_keys", + "type": "MutableSequence[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": "stop_distribution" + }, + "description": "Sample for StopDistribution", + "file": "livestream_v1_generated_livestream_service_stop_distribution_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "livestream_v1_generated_LivestreamService_StopDistribution_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_stop_distribution_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.video.live_stream_v1.LivestreamServiceClient", + "shortName": "LivestreamServiceClient" + }, + "fullName": "google.cloud.video.live_stream_v1.LivestreamServiceClient.stop_distribution", + "method": { + "fullName": "google.cloud.video.livestream.v1.LivestreamService.StopDistribution", + "service": { + "fullName": "google.cloud.video.livestream.v1.LivestreamService", + "shortName": "LivestreamService" + }, + "shortName": "StopDistribution" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.video.live_stream_v1.types.StopDistributionRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "distribution_keys", + "type": "MutableSequence[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": "stop_distribution" + }, + "description": "Sample for StopDistribution", + "file": "livestream_v1_generated_livestream_service_stop_distribution_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "livestream_v1_generated_LivestreamService_StopDistribution_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_stop_distribution_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 19f860999c3a..4ca32c834c4b 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 @@ -64,8 +64,11 @@ class live_streamCallTransformer(cst.CSTTransformer): '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', ), + 'preview_input': ('name', ), 'start_channel': ('name', 'request_id', ), + 'start_distribution': ('name', 'distribution_keys', 'request_id', ), 'stop_channel': ('name', 'request_id', ), + 'stop_distribution': ('name', 'distribution_keys', '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', ), 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 98a7ea4d6826..4002a8d4fa02 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 @@ -3698,11 +3698,11 @@ async def test_stop_channel_flattened_error_async(): @pytest.mark.parametrize( "request_type", [ - service.CreateInputRequest, + service.StartDistributionRequest, dict, ], ) -def test_create_input(request_type, transport: str = "grpc"): +def test_start_distribution(request_type, transport: str = "grpc"): client = LivestreamServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -3713,22 +3713,24 @@ def test_create_input(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_input), "__call__") as call: + with mock.patch.object( + type(client.transport.start_distribution), "__call__" + ) as call: # Designate an appropriate return value for the call. call.return_value = operations_pb2.Operation(name="operations/spam") - response = client.create_input(request) + response = client.start_distribution(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - request = service.CreateInputRequest() + request = service.StartDistributionRequest() assert args[0] == request # Establish that the response is the type that we expect. assert isinstance(response, future.Future) -def test_create_input_non_empty_request_with_auto_populated_field(): +def test_start_distribution_non_empty_request_with_auto_populated_field(): # 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( @@ -3739,28 +3741,26 @@ def test_create_input_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.CreateInputRequest( - parent="parent_value", - input_id="input_id_value", - request_id="request_id_value", + request = service.StartDistributionRequest( + name="name_value", ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.create_input), "__call__") as call: + with mock.patch.object( + type(client.transport.start_distribution), "__call__" + ) as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.create_input(request=request) + client.start_distribution(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == service.CreateInputRequest( - parent="parent_value", - input_id="input_id_value", - request_id="request_id_value", + assert args[0] == service.StartDistributionRequest( + name="name_value", ) -def test_create_input_use_cached_wrapped_rpc(): +def test_start_distribution_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -3774,16 +3774,20 @@ def test_create_input_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.create_input in client._transport._wrapped_methods + assert ( + client._transport.start_distribution in client._transport._wrapped_methods + ) # Replace cached wrapped function with mock mock_rpc = 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_input] = mock_rpc + client._transport._wrapped_methods[ + client._transport.start_distribution + ] = mock_rpc request = {} - client.create_input(request) + client.start_distribution(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 @@ -3793,7 +3797,7 @@ def test_create_input_use_cached_wrapped_rpc(): # Subsequent calls should use the cached wrapper wrapper_fn.reset_mock() - client.create_input(request) + client.start_distribution(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -3801,7 +3805,7 @@ def test_create_input_use_cached_wrapped_rpc(): @pytest.mark.asyncio -async def test_create_input_async_use_cached_wrapped_rpc( +async def test_start_distribution_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", ): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, @@ -3818,7 +3822,7 @@ async def test_create_input_async_use_cached_wrapped_rpc( # Ensure method has been cached assert ( - client._client._transport.create_input + client._client._transport.start_distribution in client._client._transport._wrapped_methods ) @@ -3826,11 +3830,11 @@ async def test_create_input_async_use_cached_wrapped_rpc( mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() client._client._transport._wrapped_methods[ - client._client._transport.create_input + client._client._transport.start_distribution ] = mock_rpc request = {} - await client.create_input(request) + await client.start_distribution(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 @@ -3840,7 +3844,7 @@ async def test_create_input_async_use_cached_wrapped_rpc( # Subsequent calls should use the cached wrapper wrapper_fn.reset_mock() - await client.create_input(request) + await client.start_distribution(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -3848,8 +3852,8 @@ async def test_create_input_async_use_cached_wrapped_rpc( @pytest.mark.asyncio -async def test_create_input_async( - transport: str = "grpc_asyncio", request_type=service.CreateInputRequest +async def test_start_distribution_async( + transport: str = "grpc_asyncio", request_type=service.StartDistributionRequest ): client = LivestreamServiceAsyncClient( credentials=async_anonymous_credentials(), @@ -3861,17 +3865,19 @@ async def test_create_input_async( request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.create_input), "__call__") as call: + with mock.patch.object( + type(client.transport.start_distribution), "__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_input(request) + response = await client.start_distribution(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request = service.CreateInputRequest() + request = service.StartDistributionRequest() assert args[0] == request # Establish that the response is the type that we expect. @@ -3879,25 +3885,27 @@ async def test_create_input_async( @pytest.mark.asyncio -async def test_create_input_async_from_dict(): - await test_create_input_async(request_type=dict) +async def test_start_distribution_async_from_dict(): + await test_start_distribution_async(request_type=dict) -def test_create_input_field_headers(): +def test_start_distribution_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.CreateInputRequest() + request = service.StartDistributionRequest() - request.parent = "parent_value" + request.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.create_input), "__call__") as call: + with mock.patch.object( + type(client.transport.start_distribution), "__call__" + ) as call: call.return_value = operations_pb2.Operation(name="operations/op") - client.create_input(request) + client.start_distribution(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 @@ -3908,28 +3916,30 @@ def test_create_input_field_headers(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "parent=parent_value", + "name=name_value", ) in kw["metadata"] @pytest.mark.asyncio -async def test_create_input_field_headers_async(): +async def test_start_distribution_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.CreateInputRequest() + request = service.StartDistributionRequest() - request.parent = "parent_value" + request.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.create_input), "__call__") as call: + with mock.patch.object( + type(client.transport.start_distribution), "__call__" + ) as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( operations_pb2.Operation(name="operations/op") ) - await client.create_input(request) + await client.start_distribution(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) @@ -3940,43 +3950,41 @@ async def test_create_input_field_headers_async(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "parent=parent_value", + "name=name_value", ) in kw["metadata"] -def test_create_input_flattened(): +def test_start_distribution_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_input), "__call__") as call: + with mock.patch.object( + type(client.transport.start_distribution), "__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_input( - parent="parent_value", - input=resources.Input(name="name_value"), - input_id="input_id_value", + client.start_distribution( + name="name_value", + distribution_keys=["distribution_keys_value"], ) # Establish that the underlying call was made with the expected # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - arg = args[0].parent - mock_val = "parent_value" - assert arg == mock_val - arg = args[0].input - mock_val = resources.Input(name="name_value") + arg = args[0].name + mock_val = "name_value" assert arg == mock_val - arg = args[0].input_id - mock_val = "input_id_value" + arg = args[0].distribution_keys + mock_val = ["distribution_keys_value"] assert arg == mock_val -def test_create_input_flattened_error(): +def test_start_distribution_flattened_error(): client = LivestreamServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -3984,22 +3992,23 @@ def test_create_input_flattened_error(): # 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.start_distribution( + service.StartDistributionRequest(), + name="name_value", + distribution_keys=["distribution_keys_value"], ) @pytest.mark.asyncio -async def test_create_input_flattened_async(): +async def test_start_distribution_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_input), "__call__") as call: + with mock.patch.object( + type(client.transport.start_distribution), "__call__" + ) as call: # Designate an appropriate return value for the call. call.return_value = operations_pb2.Operation(name="operations/op") @@ -4008,29 +4017,25 @@ async def test_create_input_flattened_async(): ) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - response = await client.create_input( - parent="parent_value", - input=resources.Input(name="name_value"), - input_id="input_id_value", + response = await client.start_distribution( + name="name_value", + distribution_keys=["distribution_keys_value"], ) # Establish that the underlying call was made with the expected # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - arg = args[0].parent - mock_val = "parent_value" - assert arg == mock_val - arg = args[0].input - mock_val = resources.Input(name="name_value") + arg = args[0].name + mock_val = "name_value" assert arg == mock_val - arg = args[0].input_id - mock_val = "input_id_value" + arg = args[0].distribution_keys + mock_val = ["distribution_keys_value"] assert arg == mock_val @pytest.mark.asyncio -async def test_create_input_flattened_error_async(): +async def test_start_distribution_flattened_error_async(): client = LivestreamServiceAsyncClient( credentials=async_anonymous_credentials(), ) @@ -4038,22 +4043,21 @@ async def test_create_input_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_input( - service.CreateInputRequest(), - parent="parent_value", - input=resources.Input(name="name_value"), - input_id="input_id_value", + await client.start_distribution( + service.StartDistributionRequest(), + name="name_value", + distribution_keys=["distribution_keys_value"], ) @pytest.mark.parametrize( "request_type", [ - service.ListInputsRequest, + service.StopDistributionRequest, dict, ], ) -def test_list_inputs(request_type, transport: str = "grpc"): +def test_stop_distribution(request_type, transport: str = "grpc"): client = LivestreamServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -4064,27 +4068,24 @@ def test_list_inputs(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_inputs), "__call__") as call: + with mock.patch.object( + type(client.transport.stop_distribution), "__call__" + ) as call: # Designate an appropriate return value for the call. - call.return_value = service.ListInputsResponse( - next_page_token="next_page_token_value", - unreachable=["unreachable_value"], - ) - response = client.list_inputs(request) + call.return_value = operations_pb2.Operation(name="operations/spam") + response = client.stop_distribution(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - request = service.ListInputsRequest() + request = service.StopDistributionRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListInputsPager) - assert response.next_page_token == "next_page_token_value" - assert response.unreachable == ["unreachable_value"] + assert isinstance(response, future.Future) -def test_list_inputs_non_empty_request_with_auto_populated_field(): +def test_stop_distribution_non_empty_request_with_auto_populated_field(): # 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( @@ -4095,30 +4096,26 @@ def test_list_inputs_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.ListInputsRequest( - parent="parent_value", - page_token="page_token_value", - filter="filter_value", - order_by="order_by_value", + request = service.StopDistributionRequest( + name="name_value", ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_inputs), "__call__") as call: + with mock.patch.object( + type(client.transport.stop_distribution), "__call__" + ) as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.list_inputs(request=request) + client.stop_distribution(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == service.ListInputsRequest( - parent="parent_value", - page_token="page_token_value", - filter="filter_value", - order_by="order_by_value", + assert args[0] == service.StopDistributionRequest( + name="name_value", ) -def test_list_inputs_use_cached_wrapped_rpc(): +def test_stop_distribution_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -4132,21 +4129,28 @@ def test_list_inputs_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.stop_distribution in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = 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.stop_distribution + ] = mock_rpc request = {} - client.list_inputs(request) + client.stop_distribution(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.stop_distribution(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -4154,7 +4158,7 @@ def test_list_inputs_use_cached_wrapped_rpc(): @pytest.mark.asyncio -async def test_list_inputs_async_use_cached_wrapped_rpc( +async def test_stop_distribution_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", ): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, @@ -4171,7 +4175,7 @@ async def test_list_inputs_async_use_cached_wrapped_rpc( # Ensure method has been cached assert ( - client._client._transport.list_inputs + client._client._transport.stop_distribution in client._client._transport._wrapped_methods ) @@ -4179,16 +4183,21 @@ async def test_list_inputs_async_use_cached_wrapped_rpc( mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() client._client._transport._wrapped_methods[ - client._client._transport.list_inputs + client._client._transport.stop_distribution ] = mock_rpc request = {} - await client.list_inputs(request) + await client.stop_distribution(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - await 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() + + await client.stop_distribution(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -4196,8 +4205,8 @@ async def test_list_inputs_async_use_cached_wrapped_rpc( @pytest.mark.asyncio -async def test_list_inputs_async( - transport: str = "grpc_asyncio", request_type=service.ListInputsRequest +async def test_stop_distribution_async( + transport: str = "grpc_asyncio", request_type=service.StopDistributionRequest ): client = LivestreamServiceAsyncClient( credentials=async_anonymous_credentials(), @@ -4209,48 +4218,47 @@ async def test_list_inputs_async( request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_inputs), "__call__") as call: + with mock.patch.object( + type(client.transport.stop_distribution), "__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"], - ) + operations_pb2.Operation(name="operations/spam") ) - response = await client.list_inputs(request) + response = await client.stop_distribution(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request = service.ListInputsRequest() + request = service.StopDistributionRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListInputsAsyncPager) - 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_inputs_async_from_dict(): - await test_list_inputs_async(request_type=dict) +async def test_stop_distribution_async_from_dict(): + await test_stop_distribution_async(request_type=dict) -def test_list_inputs_field_headers(): +def test_stop_distribution_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.ListInputsRequest() + request = service.StopDistributionRequest() - 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_inputs), "__call__") as call: - call.return_value = service.ListInputsResponse() - client.list_inputs(request) + with mock.patch.object( + type(client.transport.stop_distribution), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.stop_distribution(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 @@ -4261,28 +4269,30 @@ def test_list_inputs_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_inputs_field_headers_async(): +async def test_stop_distribution_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.ListInputsRequest() + request = service.StopDistributionRequest() - 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_inputs), "__call__") as call: + with mock.patch.object( + type(client.transport.stop_distribution), "__call__" + ) as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - service.ListInputsResponse() + operations_pb2.Operation(name="operations/op") ) - await client.list_inputs(request) + await client.stop_distribution(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) @@ -4293,35 +4303,41 @@ async def test_list_inputs_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_inputs_flattened(): +def test_stop_distribution_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_inputs), "__call__") as call: + with mock.patch.object( + type(client.transport.stop_distribution), "__call__" + ) as call: # Designate an appropriate return value for the call. - call.return_value = service.ListInputsResponse() + 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_inputs( - parent="parent_value", + client.stop_distribution( + name="name_value", + distribution_keys=["distribution_keys_value"], ) # Establish that the underlying call was made with the expected # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - arg = args[0].parent - mock_val = "parent_value" + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + arg = args[0].distribution_keys + mock_val = ["distribution_keys_value"] assert arg == mock_val -def test_list_inputs_flattened_error(): +def test_stop_distribution_flattened_error(): client = LivestreamServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -4329,43 +4345,50 @@ def test_list_inputs_flattened_error(): # 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.stop_distribution( + service.StopDistributionRequest(), + name="name_value", + distribution_keys=["distribution_keys_value"], ) @pytest.mark.asyncio -async def test_list_inputs_flattened_async(): +async def test_stop_distribution_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_inputs), "__call__") as call: + with mock.patch.object( + type(client.transport.stop_distribution), "__call__" + ) as call: # Designate an appropriate return value for the call. - call.return_value = service.ListInputsResponse() + call.return_value = operations_pb2.Operation(name="operations/op") call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - service.ListInputsResponse() + 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_inputs( - parent="parent_value", + response = await client.stop_distribution( + name="name_value", + distribution_keys=["distribution_keys_value"], ) # Establish that the underlying call was made with the expected # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - arg = args[0].parent - mock_val = "parent_value" + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + arg = args[0].distribution_keys + mock_val = ["distribution_keys_value"] assert arg == mock_val @pytest.mark.asyncio -async def test_list_inputs_flattened_error_async(): +async def test_stop_distribution_flattened_error_async(): client = LivestreamServiceAsyncClient( credentials=async_anonymous_credentials(), ) @@ -4373,214 +4396,21 @@ async def test_list_inputs_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_inputs( - service.ListInputsRequest(), - parent="parent_value", + await client.stop_distribution( + service.StopDistributionRequest(), + name="name_value", + distribution_keys=["distribution_keys_value"], ) -def test_list_inputs_pager(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_inputs), "__call__") as call: - # Set the response to a series of pages. - call.side_effect = ( - 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(), - ], - ), - RuntimeError, - ) - - expected_metadata = () - retry = retries.Retry() - timeout = 5 - expected_metadata = tuple(expected_metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)), - ) - pager = client.list_inputs(request={}, retry=retry, timeout=timeout) - - assert pager._metadata == expected_metadata - assert pager._retry == retry - assert pager._timeout == timeout - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, resources.Input) for i in results) - - -def test_list_inputs_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_inputs), "__call__") as call: - # Set the response to a series of pages. - call.side_effect = ( - 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(), - ], - ), - RuntimeError, - ) - pages = list(client.list_inputs(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_inputs_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_inputs), "__call__", new_callable=mock.AsyncMock - ) as call: - # Set the response to a series of pages. - call.side_effect = ( - 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(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_inputs( - 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.Input) for i in responses) - - -@pytest.mark.asyncio -async def test_list_inputs_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_inputs), "__call__", new_callable=mock.AsyncMock - ) as call: - # Set the response to a series of pages. - call.side_effect = ( - 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(), - ], - ), - 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_inputs(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.GetInputRequest, + service.CreateInputRequest, dict, ], ) -def test_get_input(request_type, transport: str = "grpc"): +def test_create_input(request_type, transport: str = "grpc"): client = LivestreamServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -4591,31 +4421,22 @@ def test_get_input(request_type, transport: str = "grpc"): request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_input), "__call__") as call: + with mock.patch.object(type(client.transport.create_input), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = resources.Input( - name="name_value", - type_=resources.Input.Type.RTMP_PUSH, - tier=resources.Input.Tier.SD, - uri="uri_value", - ) - response = client.get_input(request) + call.return_value = operations_pb2.Operation(name="operations/spam") + response = client.create_input(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - request = service.GetInputRequest() + request = service.CreateInputRequest() assert args[0] == 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 isinstance(response, future.Future) -def test_get_input_non_empty_request_with_auto_populated_field(): +def test_create_input_non_empty_request_with_auto_populated_field(): # 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( @@ -4626,24 +4447,28 @@ def test_get_input_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.GetInputRequest( - name="name_value", + request = service.CreateInputRequest( + parent="parent_value", + input_id="input_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.get_input), "__call__") as call: + with mock.patch.object(type(client.transport.create_input), "__call__") as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.get_input(request=request) + client.create_input(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == service.GetInputRequest( - name="name_value", + assert args[0] == service.CreateInputRequest( + parent="parent_value", + input_id="input_id_value", + request_id="request_id_value", ) -def test_get_input_use_cached_wrapped_rpc(): +def test_create_input_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -4657,21 +4482,26 @@ def test_get_input_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_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 + client._transport._wrapped_methods[client._transport.create_input] = mock_rpc request = {} - client.get_input(request) + client.create_input(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.get_input(request) + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.create_input(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -4679,7 +4509,9 @@ def test_get_input_use_cached_wrapped_rpc(): @pytest.mark.asyncio -async def test_get_input_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): +async def test_create_input_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: @@ -4694,7 +4526,7 @@ async def test_get_input_async_use_cached_wrapped_rpc(transport: str = "grpc_asy # Ensure method has been cached assert ( - client._client._transport.get_input + client._client._transport.create_input in client._client._transport._wrapped_methods ) @@ -4702,16 +4534,21 @@ async def test_get_input_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_input + client._client._transport.create_input ] = mock_rpc request = {} - await client.get_input(request) + await client.create_input(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - await client.get_input(request) + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.create_input(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -4719,8 +4556,8 @@ async def test_get_input_async_use_cached_wrapped_rpc(transport: str = "grpc_asy @pytest.mark.asyncio -async def test_get_input_async( - transport: str = "grpc_asyncio", request_type=service.GetInputRequest +async def test_create_input_async( + transport: str = "grpc_asyncio", request_type=service.CreateInputRequest ): client = LivestreamServiceAsyncClient( credentials=async_anonymous_credentials(), @@ -4732,52 +4569,43 @@ async def test_get_input_async( request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_input), "__call__") as call: + 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( - resources.Input( - name="name_value", - type_=resources.Input.Type.RTMP_PUSH, - tier=resources.Input.Tier.SD, - uri="uri_value", - ) + operations_pb2.Operation(name="operations/spam") ) - response = await client.get_input(request) + response = await client.create_input(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request = service.GetInputRequest() + request = service.CreateInputRequest() assert args[0] == 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 isinstance(response, future.Future) @pytest.mark.asyncio -async def test_get_input_async_from_dict(): - await test_get_input_async(request_type=dict) +async def test_create_input_async_from_dict(): + await test_create_input_async(request_type=dict) -def test_get_input_field_headers(): +def test_create_input_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.GetInputRequest() + request = service.CreateInputRequest() - request.name = "name_value" + request.parent = "parent_value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_input), "__call__") as call: - call.return_value = resources.Input() - client.get_input(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) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 @@ -4788,26 +4616,28 @@ def test_get_input_field_headers(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "name=name_value", + "parent=parent_value", ) in kw["metadata"] @pytest.mark.asyncio -async def test_get_input_field_headers_async(): +async def test_create_input_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.GetInputRequest() + request = service.CreateInputRequest() - request.name = "name_value" + request.parent = "parent_value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_input), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.Input()) - await client.get_input(request) + with mock.patch.object(type(client.transport.create_input), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/op") + ) + await client.create_input(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) @@ -4818,35 +4648,43 @@ async def test_get_input_field_headers_async(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "name=name_value", + "parent=parent_value", ) in kw["metadata"] -def test_get_input_flattened(): +def test_create_input_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_input), "__call__") as call: + with mock.patch.object(type(client.transport.create_input), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = resources.Input() + 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_input( - name="name_value", + client.create_input( + parent="parent_value", + input=resources.Input(name="name_value"), + input_id="input_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].name - mock_val = "name_value" + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + arg = args[0].input + mock_val = resources.Input(name="name_value") + assert arg == mock_val + arg = args[0].input_id + mock_val = "input_id_value" assert arg == mock_val -def test_get_input_flattened_error(): +def test_create_input_flattened_error(): client = LivestreamServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -4854,41 +4692,53 @@ def test_get_input_flattened_error(): # 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_input( + service.CreateInputRequest(), + parent="parent_value", + input=resources.Input(name="name_value"), + input_id="input_id_value", ) @pytest.mark.asyncio -async def test_get_input_flattened_async(): +async def test_create_input_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_input), "__call__") as call: + with mock.patch.object(type(client.transport.create_input), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = resources.Input() + call.return_value = operations_pb2.Operation(name="operations/op") - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.Input()) + 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_input( - name="name_value", + response = await client.create_input( + parent="parent_value", + input=resources.Input(name="name_value"), + input_id="input_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].name - mock_val = "name_value" + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + arg = args[0].input + mock_val = resources.Input(name="name_value") + assert arg == mock_val + arg = args[0].input_id + mock_val = "input_id_value" assert arg == mock_val @pytest.mark.asyncio -async def test_get_input_flattened_error_async(): +async def test_create_input_flattened_error_async(): client = LivestreamServiceAsyncClient( credentials=async_anonymous_credentials(), ) @@ -4896,20 +4746,22 @@ async def test_get_input_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_input( - service.GetInputRequest(), - name="name_value", + await client.create_input( + service.CreateInputRequest(), + parent="parent_value", + input=resources.Input(name="name_value"), + input_id="input_id_value", ) @pytest.mark.parametrize( "request_type", [ - service.DeleteInputRequest, + service.ListInputsRequest, dict, ], ) -def test_delete_input(request_type, transport: str = "grpc"): +def test_list_inputs(request_type, transport: str = "grpc"): client = LivestreamServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -4920,22 +4772,27 @@ def test_delete_input(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_input), "__call__") as call: + with mock.patch.object(type(client.transport.list_inputs), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name="operations/spam") - response = client.delete_input(request) + call.return_value = service.ListInputsResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], + ) + response = client.list_inputs(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - request = service.DeleteInputRequest() + request = service.ListInputsRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) + assert isinstance(response, pagers.ListInputsPager) + assert response.next_page_token == "next_page_token_value" + assert response.unreachable == ["unreachable_value"] -def test_delete_input_non_empty_request_with_auto_populated_field(): +def test_list_inputs_non_empty_request_with_auto_populated_field(): # 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( @@ -4946,26 +4803,30 @@ def test_delete_input_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.DeleteInputRequest( - name="name_value", - request_id="request_id_value", + request = service.ListInputsRequest( + 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_input), "__call__") as call: + with mock.patch.object(type(client.transport.list_inputs), "__call__") as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.delete_input(request=request) + client.list_inputs(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == service.DeleteInputRequest( - name="name_value", - request_id="request_id_value", + assert args[0] == service.ListInputsRequest( + parent="parent_value", + page_token="page_token_value", + filter="filter_value", + order_by="order_by_value", ) -def test_delete_input_use_cached_wrapped_rpc(): +def test_list_inputs_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -4979,26 +4840,21 @@ def test_delete_input_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_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.delete_input] = mock_rpc + client._transport._wrapped_methods[client._transport.list_inputs] = mock_rpc request = {} - client.delete_input(request) + client.list_inputs(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_input(request) + client.list_inputs(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -5006,7 +4862,7 @@ def test_delete_input_use_cached_wrapped_rpc(): @pytest.mark.asyncio -async def test_delete_input_async_use_cached_wrapped_rpc( +async def test_list_inputs_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", ): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, @@ -5023,7 +4879,7 @@ async def test_delete_input_async_use_cached_wrapped_rpc( # Ensure method has been cached assert ( - client._client._transport.delete_input + client._client._transport.list_inputs in client._client._transport._wrapped_methods ) @@ -5031,21 +4887,16 @@ async def test_delete_input_async_use_cached_wrapped_rpc( mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() client._client._transport._wrapped_methods[ - client._client._transport.delete_input + client._client._transport.list_inputs ] = mock_rpc request = {} - await client.delete_input(request) + await client.list_inputs(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_input(request) + await client.list_inputs(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -5053,8 +4904,8 @@ async def test_delete_input_async_use_cached_wrapped_rpc( @pytest.mark.asyncio -async def test_delete_input_async( - transport: str = "grpc_asyncio", request_type=service.DeleteInputRequest +async def test_list_inputs_async( + transport: str = "grpc_asyncio", request_type=service.ListInputsRequest ): client = LivestreamServiceAsyncClient( credentials=async_anonymous_credentials(), @@ -5066,43 +4917,48 @@ async def test_delete_input_async( request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.delete_input), "__call__") as call: + 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( - operations_pb2.Operation(name="operations/spam") + service.ListInputsResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], + ) ) - response = await client.delete_input(request) + response = await client.list_inputs(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request = service.DeleteInputRequest() + request = service.ListInputsRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) + assert isinstance(response, pagers.ListInputsAsyncPager) + assert response.next_page_token == "next_page_token_value" + assert response.unreachable == ["unreachable_value"] @pytest.mark.asyncio -async def test_delete_input_async_from_dict(): - await test_delete_input_async(request_type=dict) +async def test_list_inputs_async_from_dict(): + await test_list_inputs_async(request_type=dict) -def test_delete_input_field_headers(): +def test_list_inputs_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.DeleteInputRequest() + request = service.ListInputsRequest() - 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_input), "__call__") as call: - call.return_value = operations_pb2.Operation(name="operations/op") - client.delete_input(request) + with mock.patch.object(type(client.transport.list_inputs), "__call__") as call: + call.return_value = service.ListInputsResponse() + client.list_inputs(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 @@ -5113,28 +4969,28 @@ def test_delete_input_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_input_field_headers_async(): +async def test_list_inputs_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.DeleteInputRequest() + request = service.ListInputsRequest() - 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_input), "__call__") as call: + with mock.patch.object(type(client.transport.list_inputs), "__call__") as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/op") + service.ListInputsResponse() ) - await client.delete_input(request) + await client.list_inputs(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) @@ -5145,35 +5001,35 @@ async def test_delete_input_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_input_flattened(): +def test_list_inputs_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_input), "__call__") as call: + with mock.patch.object(type(client.transport.list_inputs), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name="operations/op") + call.return_value = service.ListInputsResponse() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - client.delete_input( - name="name_value", + client.list_inputs( + 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_input_flattened_error(): +def test_list_inputs_flattened_error(): client = LivestreamServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -5181,43 +5037,43 @@ def test_delete_input_flattened_error(): # 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", + client.list_inputs( + service.ListInputsRequest(), + parent="parent_value", ) @pytest.mark.asyncio -async def test_delete_input_flattened_async(): +async def test_list_inputs_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_input), "__call__") as call: + with mock.patch.object(type(client.transport.list_inputs), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name="operations/op") + call.return_value = service.ListInputsResponse() call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") + service.ListInputsResponse() ) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - response = await client.delete_input( - name="name_value", + response = await client.list_inputs( + 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_input_flattened_error_async(): +async def test_list_inputs_flattened_error_async(): client = LivestreamServiceAsyncClient( credentials=async_anonymous_credentials(), ) @@ -5225,20 +5081,214 @@ async def test_delete_input_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_input( - service.DeleteInputRequest(), - name="name_value", + await client.list_inputs( + service.ListInputsRequest(), + parent="parent_value", + ) + + +def test_list_inputs_pager(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_inputs), "__call__") as call: + # Set the response to a series of pages. + call.side_effect = ( + 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(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)), + ) + pager = client.list_inputs(request={}, retry=retry, timeout=timeout) + + assert pager._metadata == expected_metadata + assert pager._retry == retry + assert pager._timeout == timeout + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, resources.Input) for i in results) + + +def test_list_inputs_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_inputs), "__call__") as call: + # Set the response to a series of pages. + call.side_effect = ( + 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(), + ], + ), + RuntimeError, + ) + pages = list(client.list_inputs(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_inputs_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_inputs), "__call__", new_callable=mock.AsyncMock + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + 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(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_inputs( + 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.Input) for i in responses) + + +@pytest.mark.asyncio +async def test_list_inputs_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_inputs), "__call__", new_callable=mock.AsyncMock + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + 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(), + ], + ), + 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_inputs(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.UpdateInputRequest, + service.GetInputRequest, dict, ], ) -def test_update_input(request_type, transport: str = "grpc"): +def test_get_input(request_type, transport: str = "grpc"): client = LivestreamServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -5249,22 +5299,31 @@ def test_update_input(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_input), "__call__") as call: + with mock.patch.object(type(client.transport.get_input), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name="operations/spam") - response = client.update_input(request) + call.return_value = resources.Input( + name="name_value", + type_=resources.Input.Type.RTMP_PUSH, + tier=resources.Input.Tier.SD, + uri="uri_value", + ) + response = client.get_input(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - request = service.UpdateInputRequest() + request = service.GetInputRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) + 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" -def test_update_input_non_empty_request_with_auto_populated_field(): +def test_get_input_non_empty_request_with_auto_populated_field(): # 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( @@ -5275,24 +5334,24 @@ def test_update_input_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.UpdateInputRequest( - request_id="request_id_value", + request = service.GetInputRequest( + name="name_value", ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.update_input), "__call__") as call: + with mock.patch.object(type(client.transport.get_input), "__call__") as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.update_input(request=request) + client.get_input(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == service.UpdateInputRequest( - request_id="request_id_value", + assert args[0] == service.GetInputRequest( + name="name_value", ) -def test_update_input_use_cached_wrapped_rpc(): +def test_get_input_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -5306,26 +5365,21 @@ def test_update_input_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.update_input in client._transport._wrapped_methods + 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.update_input] = mock_rpc + client._transport._wrapped_methods[client._transport.get_input] = mock_rpc request = {} - client.update_input(request) + client.get_input(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - # Operation methods call wrapper_fn to build a cached - # client._transport.operations_client instance on first rpc call. - # Subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() - - client.update_input(request) + client.get_input(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -5333,9 +5387,7 @@ def test_update_input_use_cached_wrapped_rpc(): @pytest.mark.asyncio -async def test_update_input_async_use_cached_wrapped_rpc( - transport: str = "grpc_asyncio", -): +async def test_get_input_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: @@ -5350,7 +5402,7 @@ async def test_update_input_async_use_cached_wrapped_rpc( # Ensure method has been cached assert ( - client._client._transport.update_input + client._client._transport.get_input in client._client._transport._wrapped_methods ) @@ -5358,21 +5410,16 @@ async def test_update_input_async_use_cached_wrapped_rpc( mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() client._client._transport._wrapped_methods[ - client._client._transport.update_input + client._client._transport.get_input ] = mock_rpc request = {} - await client.update_input(request) + await client.get_input(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - # Operation methods call wrapper_fn to build a cached - # client._transport.operations_client instance on first rpc call. - # Subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() - - await client.update_input(request) + await client.get_input(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -5380,8 +5427,8 @@ async def test_update_input_async_use_cached_wrapped_rpc( @pytest.mark.asyncio -async def test_update_input_async( - transport: str = "grpc_asyncio", request_type=service.UpdateInputRequest +async def test_get_input_async( + transport: str = "grpc_asyncio", request_type=service.GetInputRequest ): client = LivestreamServiceAsyncClient( credentials=async_anonymous_credentials(), @@ -5393,43 +5440,52 @@ async def test_update_input_async( request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.update_input), "__call__") as call: + 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( - operations_pb2.Operation(name="operations/spam") + resources.Input( + name="name_value", + type_=resources.Input.Type.RTMP_PUSH, + tier=resources.Input.Tier.SD, + uri="uri_value", + ) ) - response = await client.update_input(request) + response = await client.get_input(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request = service.UpdateInputRequest() + request = service.GetInputRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) + 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.asyncio -async def test_update_input_async_from_dict(): - await test_update_input_async(request_type=dict) +async def test_get_input_async_from_dict(): + await test_get_input_async(request_type=dict) -def test_update_input_field_headers(): +def test_get_input_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.UpdateInputRequest() + request = service.GetInputRequest() - request.input.name = "name_value" + request.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.update_input), "__call__") as call: - call.return_value = operations_pb2.Operation(name="operations/op") - client.update_input(request) + with mock.patch.object(type(client.transport.get_input), "__call__") as call: + call.return_value = resources.Input() + client.get_input(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 @@ -5440,28 +5496,26 @@ def test_update_input_field_headers(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "input.name=name_value", + "name=name_value", ) in kw["metadata"] @pytest.mark.asyncio -async def test_update_input_field_headers_async(): +async def test_get_input_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.UpdateInputRequest() + request = service.GetInputRequest() - request.input.name = "name_value" + request.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.update_input), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/op") - ) - await client.update_input(request) + with mock.patch.object(type(client.transport.get_input), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.Input()) + await client.get_input(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) @@ -5472,39 +5526,35 @@ async def test_update_input_field_headers_async(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "input.name=name_value", + "name=name_value", ) in kw["metadata"] -def test_update_input_flattened(): +def test_get_input_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_input), "__call__") as call: + with mock.patch.object(type(client.transport.get_input), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name="operations/op") + call.return_value = resources.Input() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - client.update_input( - input=resources.Input(name="name_value"), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + client.get_input( + 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].input - mock_val = resources.Input(name="name_value") - assert arg == mock_val - arg = args[0].update_mask - mock_val = field_mask_pb2.FieldMask(paths=["paths_value"]) + arg = args[0].name + mock_val = "name_value" assert arg == mock_val -def test_update_input_flattened_error(): +def test_get_input_flattened_error(): client = LivestreamServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -5512,48 +5562,41 @@ def test_update_input_flattened_error(): # 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_input( + service.GetInputRequest(), + name="name_value", ) @pytest.mark.asyncio -async def test_update_input_flattened_async(): +async def test_get_input_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_input), "__call__") as call: + with mock.patch.object(type(client.transport.get_input), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name="operations/op") + call.return_value = resources.Input() - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") - ) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.Input()) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - response = await client.update_input( - input=resources.Input(name="name_value"), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + response = await client.get_input( + 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].input - mock_val = resources.Input(name="name_value") - assert arg == mock_val - arg = args[0].update_mask - mock_val = field_mask_pb2.FieldMask(paths=["paths_value"]) + arg = args[0].name + mock_val = "name_value" assert arg == mock_val @pytest.mark.asyncio -async def test_update_input_flattened_error_async(): +async def test_get_input_flattened_error_async(): client = LivestreamServiceAsyncClient( credentials=async_anonymous_credentials(), ) @@ -5561,21 +5604,20 @@ async def test_update_input_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_input( - service.UpdateInputRequest(), - input=resources.Input(name="name_value"), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + await client.get_input( + service.GetInputRequest(), + name="name_value", ) @pytest.mark.parametrize( "request_type", [ - service.CreateEventRequest, + service.DeleteInputRequest, dict, ], ) -def test_create_event(request_type, transport: str = "grpc"): +def test_delete_input(request_type, transport: str = "grpc"): client = LivestreamServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -5586,29 +5628,22 @@ def test_create_event(request_type, transport: str = "grpc"): request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.create_event), "__call__") as call: + with mock.patch.object(type(client.transport.delete_input), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = resources.Event( - name="name_value", - execute_now=True, - state=resources.Event.State.SCHEDULED, - ) - response = client.create_event(request) + call.return_value = operations_pb2.Operation(name="operations/spam") + response = client.delete_input(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - request = service.CreateEventRequest() + request = service.DeleteInputRequest() assert args[0] == 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 + assert isinstance(response, future.Future) -def test_create_event_non_empty_request_with_auto_populated_field(): +def test_delete_input_non_empty_request_with_auto_populated_field(): # 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( @@ -5619,28 +5654,26 @@ def test_create_event_non_empty_request_with_auto_populated_field(): # Populate all string fields in the request which are not UUID4 # since we want to check that UUID4 are populated automatically # if they meet the requirements of AIP 4235. - request = service.CreateEventRequest( - parent="parent_value", - event_id="event_id_value", + request = service.DeleteInputRequest( + 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.create_event), "__call__") as call: + with mock.patch.object(type(client.transport.delete_input), "__call__") as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.create_event(request=request) + client.delete_input(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == service.CreateEventRequest( - parent="parent_value", - event_id="event_id_value", + assert args[0] == service.DeleteInputRequest( + name="name_value", request_id="request_id_value", ) -def test_create_event_use_cached_wrapped_rpc(): +def test_delete_input_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -5654,21 +5687,26 @@ def test_create_event_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_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_event] = mock_rpc + client._transport._wrapped_methods[client._transport.delete_input] = mock_rpc request = {} - client.create_event(request) + client.delete_input(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.create_event(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_input(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -5676,7 +5714,7 @@ def test_create_event_use_cached_wrapped_rpc(): @pytest.mark.asyncio -async def test_create_event_async_use_cached_wrapped_rpc( +async def test_delete_input_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", ): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, @@ -5693,7 +5731,7 @@ async def test_create_event_async_use_cached_wrapped_rpc( # Ensure method has been cached assert ( - client._client._transport.create_event + client._client._transport.delete_input in client._client._transport._wrapped_methods ) @@ -5701,16 +5739,21 @@ async def test_create_event_async_use_cached_wrapped_rpc( mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() client._client._transport._wrapped_methods[ - client._client._transport.create_event + client._client._transport.delete_input ] = mock_rpc request = {} - await client.create_event(request) + await client.delete_input(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - await client.create_event(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_input(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -5718,8 +5761,8 @@ async def test_create_event_async_use_cached_wrapped_rpc( @pytest.mark.asyncio -async def test_create_event_async( - transport: str = "grpc_asyncio", request_type=service.CreateEventRequest +async def test_delete_input_async( + transport: str = "grpc_asyncio", request_type=service.DeleteInputRequest ): client = LivestreamServiceAsyncClient( credentials=async_anonymous_credentials(), @@ -5731,50 +5774,43 @@ async def test_create_event_async( request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.create_event), "__call__") as call: + 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( - resources.Event( - name="name_value", - execute_now=True, - state=resources.Event.State.SCHEDULED, - ) + operations_pb2.Operation(name="operations/spam") ) - response = await client.create_event(request) + response = await client.delete_input(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request = service.CreateEventRequest() + request = service.DeleteInputRequest() assert args[0] == 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 + assert isinstance(response, future.Future) @pytest.mark.asyncio -async def test_create_event_async_from_dict(): - await test_create_event_async(request_type=dict) +async def test_delete_input_async_from_dict(): + await test_delete_input_async(request_type=dict) -def test_create_event_field_headers(): +def test_delete_input_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.CreateEventRequest() + request = service.DeleteInputRequest() - request.parent = "parent_value" + request.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.create_event), "__call__") as call: - call.return_value = resources.Event() - client.create_event(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) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 @@ -5785,26 +5821,28 @@ def test_create_event_field_headers(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "parent=parent_value", + "name=name_value", ) in kw["metadata"] @pytest.mark.asyncio -async def test_create_event_field_headers_async(): +async def test_delete_input_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.CreateEventRequest() + request = service.DeleteInputRequest() - request.parent = "parent_value" + request.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.create_event), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.Event()) - await client.create_event(request) + with mock.patch.object(type(client.transport.delete_input), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/op") + ) + await client.delete_input(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) @@ -5815,43 +5853,35 @@ async def test_create_event_field_headers_async(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "parent=parent_value", + "name=name_value", ) in kw["metadata"] -def test_create_event_flattened(): +def test_delete_input_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_event), "__call__") as call: + with mock.patch.object(type(client.transport.delete_input), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = resources.Event() + 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_event( - parent="parent_value", - event=resources.Event(name="name_value"), - event_id="event_id_value", + client.delete_input( + name="name_value", ) # Establish that the underlying call was made with the expected # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - arg = args[0].parent - mock_val = "parent_value" - assert arg == mock_val - arg = args[0].event - mock_val = resources.Event(name="name_value") - assert arg == mock_val - arg = args[0].event_id - mock_val = "event_id_value" + arg = args[0].name + mock_val = "name_value" assert arg == mock_val -def test_create_event_flattened_error(): +def test_delete_input_flattened_error(): client = LivestreamServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -5859,51 +5889,43 @@ def test_create_event_flattened_error(): # 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_input( + service.DeleteInputRequest(), + name="name_value", ) @pytest.mark.asyncio -async def test_create_event_flattened_async(): +async def test_delete_input_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_event), "__call__") as call: + with mock.patch.object(type(client.transport.delete_input), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = resources.Event() + call.return_value = operations_pb2.Operation(name="operations/op") - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.Event()) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - response = await client.create_event( - parent="parent_value", - event=resources.Event(name="name_value"), - event_id="event_id_value", + response = await client.delete_input( + name="name_value", ) # Establish that the underlying call was made with the expected # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - arg = args[0].parent - mock_val = "parent_value" - assert arg == mock_val - arg = args[0].event - mock_val = resources.Event(name="name_value") - assert arg == mock_val - arg = args[0].event_id - mock_val = "event_id_value" + arg = args[0].name + mock_val = "name_value" assert arg == mock_val @pytest.mark.asyncio -async def test_create_event_flattened_error_async(): +async def test_delete_input_flattened_error_async(): client = LivestreamServiceAsyncClient( credentials=async_anonymous_credentials(), ) @@ -5911,22 +5933,20 @@ async def test_create_event_flattened_error_async(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - await client.create_event( - service.CreateEventRequest(), - parent="parent_value", - event=resources.Event(name="name_value"), - event_id="event_id_value", + await client.delete_input( + service.DeleteInputRequest(), + name="name_value", ) @pytest.mark.parametrize( "request_type", [ - service.ListEventsRequest, + service.UpdateInputRequest, dict, ], ) -def test_list_events(request_type, transport: str = "grpc"): +def test_update_input(request_type, transport: str = "grpc"): client = LivestreamServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -5937,27 +5957,22 @@ def test_list_events(request_type, transport: str = "grpc"): request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_events), "__call__") as call: + with mock.patch.object(type(client.transport.update_input), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = service.ListEventsResponse( - next_page_token="next_page_token_value", - unreachable=["unreachable_value"], - ) - response = client.list_events(request) + call.return_value = operations_pb2.Operation(name="operations/spam") + response = client.update_input(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - request = service.ListEventsRequest() + request = service.UpdateInputRequest() assert args[0] == 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"] + assert isinstance(response, future.Future) -def test_list_events_non_empty_request_with_auto_populated_field(): +def test_update_input_non_empty_request_with_auto_populated_field(): # 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( @@ -5968,30 +5983,24 @@ def test_list_events_non_empty_request_with_auto_populated_field(): # Populate all string fields in the request which are not UUID4 # since we want to check that UUID4 are populated automatically # if they meet the requirements of AIP 4235. - request = service.ListEventsRequest( - parent="parent_value", - page_token="page_token_value", - filter="filter_value", - order_by="order_by_value", + request = service.UpdateInputRequest( + request_id="request_id_value", ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_events), "__call__") as call: + with mock.patch.object(type(client.transport.update_input), "__call__") as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.list_events(request=request) + client.update_input(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == service.ListEventsRequest( - parent="parent_value", - page_token="page_token_value", - filter="filter_value", - order_by="order_by_value", + assert args[0] == service.UpdateInputRequest( + request_id="request_id_value", ) -def test_list_events_use_cached_wrapped_rpc(): +def test_update_input_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -6005,21 +6014,26 @@ def test_list_events_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_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_events] = mock_rpc + client._transport._wrapped_methods[client._transport.update_input] = mock_rpc request = {} - client.list_events(request) + client.update_input(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.list_events(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_input(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -6027,7 +6041,7 @@ def test_list_events_use_cached_wrapped_rpc(): @pytest.mark.asyncio -async def test_list_events_async_use_cached_wrapped_rpc( +async def test_update_input_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", ): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, @@ -6044,7 +6058,7 @@ async def test_list_events_async_use_cached_wrapped_rpc( # Ensure method has been cached assert ( - client._client._transport.list_events + client._client._transport.update_input in client._client._transport._wrapped_methods ) @@ -6052,16 +6066,21 @@ async def test_list_events_async_use_cached_wrapped_rpc( mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() client._client._transport._wrapped_methods[ - client._client._transport.list_events + client._client._transport.update_input ] = mock_rpc request = {} - await client.list_events(request) + await client.update_input(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - await client.list_events(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_input(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -6069,8 +6088,8 @@ async def test_list_events_async_use_cached_wrapped_rpc( @pytest.mark.asyncio -async def test_list_events_async( - transport: str = "grpc_asyncio", request_type=service.ListEventsRequest +async def test_update_input_async( + transport: str = "grpc_asyncio", request_type=service.UpdateInputRequest ): client = LivestreamServiceAsyncClient( credentials=async_anonymous_credentials(), @@ -6082,48 +6101,43 @@ async def test_list_events_async( request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_events), "__call__") as call: + 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( - service.ListEventsResponse( - next_page_token="next_page_token_value", - unreachable=["unreachable_value"], - ) + operations_pb2.Operation(name="operations/spam") ) - response = await client.list_events(request) + response = await client.update_input(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request = service.ListEventsRequest() + request = service.UpdateInputRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListEventsAsyncPager) - 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_events_async_from_dict(): - await test_list_events_async(request_type=dict) +async def test_update_input_async_from_dict(): + await test_update_input_async(request_type=dict) -def test_list_events_field_headers(): +def test_update_input_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.ListEventsRequest() + request = service.UpdateInputRequest() - request.parent = "parent_value" + request.input.name = "name_value" # Mock the actual call within the gRPC stub, 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) + 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) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 @@ -6134,28 +6148,28 @@ def test_list_events_field_headers(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "parent=parent_value", + "input.name=name_value", ) in kw["metadata"] @pytest.mark.asyncio -async def test_list_events_field_headers_async(): +async def test_update_input_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.ListEventsRequest() + request = service.UpdateInputRequest() - request.parent = "parent_value" + request.input.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_events), "__call__") as call: + with mock.patch.object(type(client.transport.update_input), "__call__") as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - service.ListEventsResponse() + operations_pb2.Operation(name="operations/op") ) - await client.list_events(request) + await client.update_input(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) @@ -6166,35 +6180,39 @@ async def test_list_events_field_headers_async(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "parent=parent_value", + "input.name=name_value", ) in kw["metadata"] -def test_list_events_flattened(): +def test_update_input_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_events), "__call__") as call: + with mock.patch.object(type(client.transport.update_input), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = service.ListEventsResponse() + 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_events( - parent="parent_value", + client.update_input( + input=resources.Input(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) # Establish that the underlying call was made with the expected # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - arg = args[0].parent - mock_val = "parent_value" + arg = args[0].input + mock_val = resources.Input(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_events_flattened_error(): +def test_update_input_flattened_error(): client = LivestreamServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -6202,43 +6220,48 @@ def test_list_events_flattened_error(): # 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", + client.update_input( + service.UpdateInputRequest(), + input=resources.Input(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) @pytest.mark.asyncio -async def test_list_events_flattened_async(): +async def test_update_input_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_events), "__call__") as call: + with mock.patch.object(type(client.transport.update_input), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = service.ListEventsResponse() + call.return_value = operations_pb2.Operation(name="operations/op") call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - service.ListEventsResponse() + 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_events( - parent="parent_value", + response = await client.update_input( + input=resources.Input(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) # Establish that the underlying call was made with the expected # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - arg = args[0].parent - mock_val = "parent_value" + arg = args[0].input + mock_val = resources.Input(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_list_events_flattened_error_async(): +async def test_update_input_flattened_error_async(): client = LivestreamServiceAsyncClient( credentials=async_anonymous_credentials(), ) @@ -6246,214 +6269,21 @@ async def test_list_events_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_events( - service.ListEventsRequest(), - parent="parent_value", - ) - - -def test_list_events_pager(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_events), "__call__") as call: - # Set the response to a series of pages. - call.side_effect = ( - 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(), - ], - ), - RuntimeError, - ) - - expected_metadata = () - retry = retries.Retry() - timeout = 5 - expected_metadata = tuple(expected_metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)), - ) - pager = client.list_events(request={}, retry=retry, timeout=timeout) - - assert pager._metadata == expected_metadata - assert pager._retry == retry - assert pager._timeout == timeout - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, resources.Event) for i in results) - - -def test_list_events_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_events), "__call__") as call: - # Set the response to a series of pages. - call.side_effect = ( - 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(), - ], - ), - RuntimeError, - ) - pages = list(client.list_events(request={}).pages) - for page_, token in zip(pages, ["abc", "def", "ghi", ""]): - assert page_.raw_page.next_page_token == token - - -@pytest.mark.asyncio -async def test_list_events_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_events), "__call__", new_callable=mock.AsyncMock - ) as call: - # Set the response to a series of pages. - call.side_effect = ( - 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(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_events( - request={}, - ) - assert async_pager.next_page_token == "abc" - responses = [] - async for response in async_pager: # pragma: no branch - responses.append(response) - - assert len(responses) == 6 - assert all(isinstance(i, resources.Event) for i in responses) - - -@pytest.mark.asyncio -async def test_list_events_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_events), "__call__", new_callable=mock.AsyncMock - ) as call: - # Set the response to a series of pages. - call.side_effect = ( - 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(), - ], - ), - RuntimeError, + await client.update_input( + service.UpdateInputRequest(), + input=resources.Input(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) - 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_events(request={}) - ).pages: - pages.append(page_) - for page_, token in zip(pages, ["abc", "def", "ghi", ""]): - assert page_.raw_page.next_page_token == token @pytest.mark.parametrize( "request_type", [ - service.GetEventRequest, + service.PreviewInputRequest, dict, ], ) -def test_get_event(request_type, transport: str = "grpc"): +def test_preview_input(request_type, transport: str = "grpc"): client = LivestreamServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -6464,29 +6294,27 @@ def test_get_event(request_type, transport: str = "grpc"): request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_event), "__call__") as call: + with mock.patch.object(type(client.transport.preview_input), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = resources.Event( - name="name_value", - execute_now=True, - state=resources.Event.State.SCHEDULED, + call.return_value = service.PreviewInputResponse( + uri="uri_value", + bearer_token="bearer_token_value", ) - response = client.get_event(request) + response = client.preview_input(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - request = service.GetEventRequest() + request = service.PreviewInputRequest() assert args[0] == 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 + assert isinstance(response, service.PreviewInputResponse) + assert response.uri == "uri_value" + assert response.bearer_token == "bearer_token_value" -def test_get_event_non_empty_request_with_auto_populated_field(): +def test_preview_input_non_empty_request_with_auto_populated_field(): # 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( @@ -6497,24 +6325,24 @@ def test_get_event_non_empty_request_with_auto_populated_field(): # Populate all string fields in the request which are not UUID4 # since we want to check that UUID4 are populated automatically # if they meet the requirements of AIP 4235. - request = service.GetEventRequest( + request = service.PreviewInputRequest( name="name_value", ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_event), "__call__") as call: + with mock.patch.object(type(client.transport.preview_input), "__call__") as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.get_event(request=request) + client.preview_input(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == service.GetEventRequest( + assert args[0] == service.PreviewInputRequest( name="name_value", ) -def test_get_event_use_cached_wrapped_rpc(): +def test_preview_input_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -6528,21 +6356,21 @@ def test_get_event_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.preview_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_event] = mock_rpc + client._transport._wrapped_methods[client._transport.preview_input] = mock_rpc request = {} - client.get_event(request) + client.preview_input(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.get_event(request) + client.preview_input(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -6550,7 +6378,9 @@ def test_get_event_use_cached_wrapped_rpc(): @pytest.mark.asyncio -async def test_get_event_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): +async def test_preview_input_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: @@ -6565,7 +6395,7 @@ async def test_get_event_async_use_cached_wrapped_rpc(transport: str = "grpc_asy # Ensure method has been cached assert ( - client._client._transport.get_event + client._client._transport.preview_input in client._client._transport._wrapped_methods ) @@ -6573,16 +6403,16 @@ async def test_get_event_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_event + client._client._transport.preview_input ] = mock_rpc request = {} - await client.get_event(request) + await client.preview_input(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - await client.get_event(request) + await client.preview_input(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -6590,8 +6420,8 @@ async def test_get_event_async_use_cached_wrapped_rpc(transport: str = "grpc_asy @pytest.mark.asyncio -async def test_get_event_async( - transport: str = "grpc_asyncio", request_type=service.GetEventRequest +async def test_preview_input_async( + transport: str = "grpc_asyncio", request_type=service.PreviewInputRequest ): client = LivestreamServiceAsyncClient( credentials=async_anonymous_credentials(), @@ -6603,50 +6433,48 @@ async def test_get_event_async( request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_event), "__call__") as call: + with mock.patch.object(type(client.transport.preview_input), "__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, + service.PreviewInputResponse( + uri="uri_value", + bearer_token="bearer_token_value", ) ) - response = await client.get_event(request) + response = await client.preview_input(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request = service.GetEventRequest() + request = service.PreviewInputRequest() assert args[0] == 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 + assert isinstance(response, service.PreviewInputResponse) + assert response.uri == "uri_value" + assert response.bearer_token == "bearer_token_value" @pytest.mark.asyncio -async def test_get_event_async_from_dict(): - await test_get_event_async(request_type=dict) +async def test_preview_input_async_from_dict(): + await test_preview_input_async(request_type=dict) -def test_get_event_field_headers(): +def test_preview_input_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.GetEventRequest() + request = service.PreviewInputRequest() request.name = "name_value" # Mock the actual call within the gRPC stub, 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) + with mock.patch.object(type(client.transport.preview_input), "__call__") as call: + call.return_value = service.PreviewInputResponse() + client.preview_input(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 @@ -6662,21 +6490,23 @@ def test_get_event_field_headers(): @pytest.mark.asyncio -async def test_get_event_field_headers_async(): +async def test_preview_input_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.GetEventRequest() + request = service.PreviewInputRequest() request.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_event), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.Event()) - await client.get_event(request) + with mock.patch.object(type(client.transport.preview_input), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + service.PreviewInputResponse() + ) + await client.preview_input(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) @@ -6691,18 +6521,18 @@ async def test_get_event_field_headers_async(): ) in kw["metadata"] -def test_get_event_flattened(): +def test_preview_input_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_event), "__call__") as call: + with mock.patch.object(type(client.transport.preview_input), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = resources.Event() + call.return_value = service.PreviewInputResponse() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - client.get_event( + client.preview_input( name="name_value", ) @@ -6715,7 +6545,7 @@ def test_get_event_flattened(): assert arg == mock_val -def test_get_event_flattened_error(): +def test_preview_input_flattened_error(): client = LivestreamServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -6723,27 +6553,29 @@ def test_get_event_flattened_error(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.get_event( - service.GetEventRequest(), + client.preview_input( + service.PreviewInputRequest(), name="name_value", ) @pytest.mark.asyncio -async def test_get_event_flattened_async(): +async def test_preview_input_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_event), "__call__") as call: + with mock.patch.object(type(client.transport.preview_input), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = resources.Event() + call.return_value = service.PreviewInputResponse() - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.Event()) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + service.PreviewInputResponse() + ) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - response = await client.get_event( + response = await client.preview_input( name="name_value", ) @@ -6757,7 +6589,7 @@ async def test_get_event_flattened_async(): @pytest.mark.asyncio -async def test_get_event_flattened_error_async(): +async def test_preview_input_flattened_error_async(): client = LivestreamServiceAsyncClient( credentials=async_anonymous_credentials(), ) @@ -6765,8 +6597,8 @@ async def test_get_event_flattened_error_async(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - await client.get_event( - service.GetEventRequest(), + await client.preview_input( + service.PreviewInputRequest(), name="name_value", ) @@ -6774,11 +6606,11 @@ async def test_get_event_flattened_error_async(): @pytest.mark.parametrize( "request_type", [ - service.DeleteEventRequest, + service.CreateEventRequest, dict, ], ) -def test_delete_event(request_type, transport: str = "grpc"): +def test_create_event(request_type, transport: str = "grpc"): client = LivestreamServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -6789,22 +6621,29 @@ def test_delete_event(request_type, transport: str = "grpc"): request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.delete_event), "__call__") as call: + with mock.patch.object(type(client.transport.create_event), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = None - response = client.delete_event(request) + call.return_value = resources.Event( + name="name_value", + execute_now=True, + state=resources.Event.State.SCHEDULED, + ) + response = client.create_event(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - request = service.DeleteEventRequest() + request = service.CreateEventRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert response is None + assert isinstance(response, resources.Event) + assert response.name == "name_value" + assert response.execute_now is True + assert response.state == resources.Event.State.SCHEDULED -def test_delete_event_non_empty_request_with_auto_populated_field(): +def test_create_event_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. client = LivestreamServiceClient( @@ -6815,26 +6654,28 @@ def test_delete_event_non_empty_request_with_auto_populated_field(): # Populate all string fields in the request which are not UUID4 # since we want to check that UUID4 are populated automatically # if they meet the requirements of AIP 4235. - request = service.DeleteEventRequest( - name="name_value", + request = service.CreateEventRequest( + parent="parent_value", + event_id="event_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.delete_event), "__call__") as call: + with mock.patch.object(type(client.transport.create_event), "__call__") as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.delete_event(request=request) + client.create_event(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == service.DeleteEventRequest( - name="name_value", + assert args[0] == service.CreateEventRequest( + parent="parent_value", + event_id="event_id_value", request_id="request_id_value", ) -def test_delete_event_use_cached_wrapped_rpc(): +def test_create_event_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -6848,21 +6689,21 @@ def test_delete_event_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.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_event] = mock_rpc + client._transport._wrapped_methods[client._transport.create_event] = mock_rpc request = {} - client.delete_event(request) + client.create_event(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.delete_event(request) + client.create_event(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -6870,7 +6711,7 @@ def test_delete_event_use_cached_wrapped_rpc(): @pytest.mark.asyncio -async def test_delete_event_async_use_cached_wrapped_rpc( +async def test_create_event_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", ): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, @@ -6887,7 +6728,7 @@ async def test_delete_event_async_use_cached_wrapped_rpc( # Ensure method has been cached assert ( - client._client._transport.delete_event + client._client._transport.create_event in client._client._transport._wrapped_methods ) @@ -6895,16 +6736,16 @@ async def test_delete_event_async_use_cached_wrapped_rpc( mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() client._client._transport._wrapped_methods[ - client._client._transport.delete_event + client._client._transport.create_event ] = mock_rpc request = {} - await client.delete_event(request) + await client.create_event(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - await client.delete_event(request) + await client.create_event(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -6912,8 +6753,8 @@ async def test_delete_event_async_use_cached_wrapped_rpc( @pytest.mark.asyncio -async def test_delete_event_async( - transport: str = "grpc_asyncio", request_type=service.DeleteEventRequest +async def test_create_event_async( + transport: str = "grpc_asyncio", request_type=service.CreateEventRequest ): client = LivestreamServiceAsyncClient( credentials=async_anonymous_credentials(), @@ -6925,41 +6766,50 @@ async def test_delete_event_async( request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.delete_event), "__call__") as call: + 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(None) - response = await client.delete_event(request) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + resources.Event( + name="name_value", + execute_now=True, + state=resources.Event.State.SCHEDULED, + ) + ) + response = await client.create_event(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request = service.DeleteEventRequest() + request = service.CreateEventRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert response is None + 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.asyncio -async def test_delete_event_async_from_dict(): - await test_delete_event_async(request_type=dict) +async def test_create_event_async_from_dict(): + await test_create_event_async(request_type=dict) -def test_delete_event_field_headers(): +def test_create_event_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.DeleteEventRequest() + request = service.CreateEventRequest() - 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_event), "__call__") as call: - call.return_value = None - client.delete_event(request) + with mock.patch.object(type(client.transport.create_event), "__call__") as call: + call.return_value = resources.Event() + client.create_event(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 @@ -6970,26 +6820,26 @@ def test_delete_event_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_event_field_headers_async(): +async def test_create_event_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.DeleteEventRequest() + request = service.CreateEventRequest() - 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_event), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.delete_event(request) + with mock.patch.object(type(client.transport.create_event), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.Event()) + await client.create_event(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) @@ -7000,35 +6850,43 @@ async def test_delete_event_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_event_flattened(): +def test_create_event_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_event), "__call__") as call: + with mock.patch.object(type(client.transport.create_event), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = None + call.return_value = resources.Event() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - client.delete_event( - name="name_value", + client.create_event( + parent="parent_value", + event=resources.Event(name="name_value"), + event_id="event_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].name - mock_val = "name_value" + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + arg = args[0].event + mock_val = resources.Event(name="name_value") + assert arg == mock_val + arg = args[0].event_id + mock_val = "event_id_value" assert arg == mock_val -def test_delete_event_flattened_error(): +def test_create_event_flattened_error(): client = LivestreamServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -7036,41 +6894,51 @@ def test_delete_event_flattened_error(): # 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(), - name="name_value", + client.create_event( + service.CreateEventRequest(), + parent="parent_value", + event=resources.Event(name="name_value"), + event_id="event_id_value", ) @pytest.mark.asyncio -async def test_delete_event_flattened_async(): +async def test_create_event_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_event), "__call__") as call: + with mock.patch.object(type(client.transport.create_event), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = None + call.return_value = resources.Event() - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.Event()) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - response = await client.delete_event( - name="name_value", + response = await client.create_event( + parent="parent_value", + event=resources.Event(name="name_value"), + event_id="event_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].name - mock_val = "name_value" + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + arg = args[0].event + mock_val = resources.Event(name="name_value") + assert arg == mock_val + arg = args[0].event_id + mock_val = "event_id_value" assert arg == mock_val @pytest.mark.asyncio -async def test_delete_event_flattened_error_async(): +async def test_create_event_flattened_error_async(): client = LivestreamServiceAsyncClient( credentials=async_anonymous_credentials(), ) @@ -7078,20 +6946,22 @@ async def test_delete_event_flattened_error_async(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - await client.delete_event( - service.DeleteEventRequest(), - name="name_value", + await client.create_event( + service.CreateEventRequest(), + parent="parent_value", + event=resources.Event(name="name_value"), + event_id="event_id_value", ) @pytest.mark.parametrize( "request_type", [ - service.ListClipsRequest, + service.ListEventsRequest, dict, ], ) -def test_list_clips(request_type, transport: str = "grpc"): +def test_list_events(request_type, transport: str = "grpc"): client = LivestreamServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -7102,27 +6972,27 @@ def test_list_clips(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_clips), "__call__") as call: + with mock.patch.object(type(client.transport.list_events), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = service.ListClipsResponse( + call.return_value = service.ListEventsResponse( next_page_token="next_page_token_value", unreachable=["unreachable_value"], ) - response = client.list_clips(request) + response = client.list_events(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - request = service.ListClipsRequest() + request = service.ListEventsRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListClipsPager) + assert isinstance(response, pagers.ListEventsPager) assert response.next_page_token == "next_page_token_value" assert response.unreachable == ["unreachable_value"] -def test_list_clips_non_empty_request_with_auto_populated_field(): +def test_list_events_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. client = LivestreamServiceClient( @@ -7133,7 +7003,7 @@ def test_list_clips_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.ListClipsRequest( + request = service.ListEventsRequest( parent="parent_value", page_token="page_token_value", filter="filter_value", @@ -7141,14 +7011,14 @@ def test_list_clips_non_empty_request_with_auto_populated_field(): ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_clips), "__call__") as call: + with mock.patch.object(type(client.transport.list_events), "__call__") as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.list_clips(request=request) + client.list_events(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == service.ListClipsRequest( + assert args[0] == service.ListEventsRequest( parent="parent_value", page_token="page_token_value", filter="filter_value", @@ -7156,7 +7026,7 @@ def test_list_clips_non_empty_request_with_auto_populated_field(): ) -def test_list_clips_use_cached_wrapped_rpc(): +def test_list_events_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -7170,21 +7040,21 @@ def test_list_clips_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.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.list_clips] = mock_rpc + client._transport._wrapped_methods[client._transport.list_events] = mock_rpc request = {} - client.list_clips(request) + client.list_events(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.list_clips(request) + client.list_events(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -7192,7 +7062,9 @@ def test_list_clips_use_cached_wrapped_rpc(): @pytest.mark.asyncio -async def test_list_clips_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): +async def test_list_events_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: @@ -7207,7 +7079,7 @@ async def test_list_clips_async_use_cached_wrapped_rpc(transport: str = "grpc_as # Ensure method has been cached assert ( - client._client._transport.list_clips + client._client._transport.list_events in client._client._transport._wrapped_methods ) @@ -7215,16 +7087,16 @@ async def test_list_clips_async_use_cached_wrapped_rpc(transport: str = "grpc_as mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() client._client._transport._wrapped_methods[ - client._client._transport.list_clips + client._client._transport.list_events ] = mock_rpc request = {} - await client.list_clips(request) + await client.list_events(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - await client.list_clips(request) + await client.list_events(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -7232,8 +7104,8 @@ async def test_list_clips_async_use_cached_wrapped_rpc(transport: str = "grpc_as @pytest.mark.asyncio -async def test_list_clips_async( - transport: str = "grpc_asyncio", request_type=service.ListClipsRequest +async def test_list_events_async( + transport: str = "grpc_asyncio", request_type=service.ListEventsRequest ): client = LivestreamServiceAsyncClient( credentials=async_anonymous_credentials(), @@ -7245,48 +7117,48 @@ async def test_list_clips_async( request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_clips), "__call__") as call: + 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.ListClipsResponse( + service.ListEventsResponse( next_page_token="next_page_token_value", unreachable=["unreachable_value"], ) ) - response = await client.list_clips(request) + response = await client.list_events(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request = service.ListClipsRequest() + request = service.ListEventsRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListClipsAsyncPager) + assert isinstance(response, pagers.ListEventsAsyncPager) assert response.next_page_token == "next_page_token_value" assert response.unreachable == ["unreachable_value"] @pytest.mark.asyncio -async def test_list_clips_async_from_dict(): - await test_list_clips_async(request_type=dict) +async def test_list_events_async_from_dict(): + await test_list_events_async(request_type=dict) -def test_list_clips_field_headers(): +def test_list_events_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.ListClipsRequest() + request = service.ListEventsRequest() request.parent = "parent_value" # Mock the actual call within the gRPC stub, 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) + with mock.patch.object(type(client.transport.list_events), "__call__") as call: + call.return_value = service.ListEventsResponse() + client.list_events(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 @@ -7302,23 +7174,23 @@ def test_list_clips_field_headers(): @pytest.mark.asyncio -async def test_list_clips_field_headers_async(): +async def test_list_events_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.ListClipsRequest() + request = service.ListEventsRequest() request.parent = "parent_value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_clips), "__call__") as call: + with mock.patch.object(type(client.transport.list_events), "__call__") as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - service.ListClipsResponse() + service.ListEventsResponse() ) - await client.list_clips(request) + await client.list_events(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) @@ -7333,18 +7205,18 @@ async def test_list_clips_field_headers_async(): ) in kw["metadata"] -def test_list_clips_flattened(): +def test_list_events_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_clips), "__call__") as call: + with mock.patch.object(type(client.transport.list_events), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = service.ListClipsResponse() + call.return_value = service.ListEventsResponse() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - client.list_clips( + client.list_events( parent="parent_value", ) @@ -7357,7 +7229,7 @@ def test_list_clips_flattened(): assert arg == mock_val -def test_list_clips_flattened_error(): +def test_list_events_flattened_error(): client = LivestreamServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -7365,29 +7237,29 @@ def test_list_clips_flattened_error(): # 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.list_events( + service.ListEventsRequest(), parent="parent_value", ) @pytest.mark.asyncio -async def test_list_clips_flattened_async(): +async def test_list_events_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_clips), "__call__") as call: + with mock.patch.object(type(client.transport.list_events), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = service.ListClipsResponse() + call.return_value = service.ListEventsResponse() call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - service.ListClipsResponse() + service.ListEventsResponse() ) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - response = await client.list_clips( + response = await client.list_events( parent="parent_value", ) @@ -7401,7 +7273,7 @@ async def test_list_clips_flattened_async(): @pytest.mark.asyncio -async def test_list_clips_flattened_error_async(): +async def test_list_events_flattened_error_async(): client = LivestreamServiceAsyncClient( credentials=async_anonymous_credentials(), ) @@ -7409,44 +7281,44 @@ async def test_list_clips_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_clips( - service.ListClipsRequest(), + await client.list_events( + service.ListEventsRequest(), parent="parent_value", ) -def test_list_clips_pager(transport_name: str = "grpc"): +def test_list_events_pager(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_clips), "__call__") as call: + with mock.patch.object(type(client.transport.list_events), "__call__") as call: # Set the response to a series of pages. call.side_effect = ( - service.ListClipsResponse( - clips=[ - resources.Clip(), - resources.Clip(), - resources.Clip(), + service.ListEventsResponse( + events=[ + resources.Event(), + resources.Event(), + resources.Event(), ], next_page_token="abc", ), - service.ListClipsResponse( - clips=[], + service.ListEventsResponse( + events=[], next_page_token="def", ), - service.ListClipsResponse( - clips=[ - resources.Clip(), + service.ListEventsResponse( + events=[ + resources.Event(), ], next_page_token="ghi", ), - service.ListClipsResponse( - clips=[ - resources.Clip(), - resources.Clip(), + service.ListEventsResponse( + events=[ + resources.Event(), + resources.Event(), ], ), RuntimeError, @@ -7458,7 +7330,7 @@ def test_list_clips_pager(transport_name: str = "grpc"): expected_metadata = tuple(expected_metadata) + ( gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)), ) - pager = client.list_clips(request={}, retry=retry, timeout=timeout) + pager = client.list_events(request={}, retry=retry, timeout=timeout) assert pager._metadata == expected_metadata assert pager._retry == retry @@ -7466,89 +7338,89 @@ def test_list_clips_pager(transport_name: str = "grpc"): results = list(pager) assert len(results) == 6 - assert all(isinstance(i, resources.Clip) for i in results) + assert all(isinstance(i, resources.Event) for i in results) -def test_list_clips_pages(transport_name: str = "grpc"): +def test_list_events_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_clips), "__call__") as call: + with mock.patch.object(type(client.transport.list_events), "__call__") as call: # Set the response to a series of pages. call.side_effect = ( - service.ListClipsResponse( - clips=[ - resources.Clip(), - resources.Clip(), - resources.Clip(), + service.ListEventsResponse( + events=[ + resources.Event(), + resources.Event(), + resources.Event(), ], next_page_token="abc", ), - service.ListClipsResponse( - clips=[], + service.ListEventsResponse( + events=[], next_page_token="def", ), - service.ListClipsResponse( - clips=[ - resources.Clip(), + service.ListEventsResponse( + events=[ + resources.Event(), ], next_page_token="ghi", ), - service.ListClipsResponse( - clips=[ - resources.Clip(), - resources.Clip(), + service.ListEventsResponse( + events=[ + resources.Event(), + resources.Event(), ], ), RuntimeError, ) - pages = list(client.list_clips(request={}).pages) + pages = list(client.list_events(request={}).pages) for page_, token in zip(pages, ["abc", "def", "ghi", ""]): assert page_.raw_page.next_page_token == token @pytest.mark.asyncio -async def test_list_clips_async_pager(): +async def test_list_events_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_clips), "__call__", new_callable=mock.AsyncMock + type(client.transport.list_events), "__call__", new_callable=mock.AsyncMock ) as call: # Set the response to a series of pages. call.side_effect = ( - service.ListClipsResponse( - clips=[ - resources.Clip(), - resources.Clip(), - resources.Clip(), + service.ListEventsResponse( + events=[ + resources.Event(), + resources.Event(), + resources.Event(), ], next_page_token="abc", ), - service.ListClipsResponse( - clips=[], + service.ListEventsResponse( + events=[], next_page_token="def", ), - service.ListClipsResponse( - clips=[ - resources.Clip(), + service.ListEventsResponse( + events=[ + resources.Event(), ], next_page_token="ghi", ), - service.ListClipsResponse( - clips=[ - resources.Clip(), - resources.Clip(), + service.ListEventsResponse( + events=[ + resources.Event(), + resources.Event(), ], ), RuntimeError, ) - async_pager = await client.list_clips( + async_pager = await client.list_events( request={}, ) assert async_pager.next_page_token == "abc" @@ -7557,43 +7429,43 @@ async def test_list_clips_async_pager(): responses.append(response) assert len(responses) == 6 - assert all(isinstance(i, resources.Clip) for i in responses) + assert all(isinstance(i, resources.Event) for i in responses) @pytest.mark.asyncio -async def test_list_clips_async_pages(): +async def test_list_events_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_clips), "__call__", new_callable=mock.AsyncMock + type(client.transport.list_events), "__call__", new_callable=mock.AsyncMock ) as call: # Set the response to a series of pages. call.side_effect = ( - service.ListClipsResponse( - clips=[ - resources.Clip(), - resources.Clip(), - resources.Clip(), + service.ListEventsResponse( + events=[ + resources.Event(), + resources.Event(), + resources.Event(), ], next_page_token="abc", ), - service.ListClipsResponse( - clips=[], + service.ListEventsResponse( + events=[], next_page_token="def", ), - service.ListClipsResponse( - clips=[ - resources.Clip(), + service.ListEventsResponse( + events=[ + resources.Event(), ], next_page_token="ghi", ), - service.ListClipsResponse( - clips=[ - resources.Clip(), - resources.Clip(), + service.ListEventsResponse( + events=[ + resources.Event(), + resources.Event(), ], ), RuntimeError, @@ -7602,7 +7474,7 @@ async def test_list_clips_async_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_clips(request={}) + await client.list_events(request={}) ).pages: pages.append(page_) for page_, token in zip(pages, ["abc", "def", "ghi", ""]): @@ -7612,11 +7484,11 @@ async def test_list_clips_async_pages(): @pytest.mark.parametrize( "request_type", [ - service.GetClipRequest, + service.GetEventRequest, dict, ], ) -def test_get_clip(request_type, transport: str = "grpc"): +def test_get_event(request_type, transport: str = "grpc"): client = LivestreamServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -7627,31 +7499,29 @@ def test_get_clip(request_type, transport: str = "grpc"): request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_clip), "__call__") as call: + with mock.patch.object(type(client.transport.get_event), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = resources.Clip( + call.return_value = resources.Event( name="name_value", - state=resources.Clip.State.PENDING, - output_uri="output_uri_value", - output_type=resources.Clip.OutputType.MANIFEST, + execute_now=True, + state=resources.Event.State.SCHEDULED, ) - response = client.get_clip(request) + response = client.get_event(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - request = service.GetClipRequest() + request = service.GetEventRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, resources.Clip) + assert isinstance(response, resources.Event) 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 + assert response.execute_now is True + assert response.state == resources.Event.State.SCHEDULED -def test_get_clip_non_empty_request_with_auto_populated_field(): +def test_get_event_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. client = LivestreamServiceClient( @@ -7662,24 +7532,24 @@ def test_get_clip_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.GetClipRequest( + request = service.GetEventRequest( name="name_value", ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_clip), "__call__") as call: + with mock.patch.object(type(client.transport.get_event), "__call__") as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.get_clip(request=request) + client.get_event(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == service.GetClipRequest( + assert args[0] == service.GetEventRequest( name="name_value", ) -def test_get_clip_use_cached_wrapped_rpc(): +def test_get_event_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -7693,21 +7563,21 @@ def test_get_clip_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.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.get_clip] = mock_rpc + client._transport._wrapped_methods[client._transport.get_event] = mock_rpc request = {} - client.get_clip(request) + client.get_event(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.get_clip(request) + client.get_event(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -7715,7 +7585,7 @@ def test_get_clip_use_cached_wrapped_rpc(): @pytest.mark.asyncio -async def test_get_clip_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): +async def test_get_event_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: @@ -7730,7 +7600,7 @@ async def test_get_clip_async_use_cached_wrapped_rpc(transport: str = "grpc_asyn # Ensure method has been cached assert ( - client._client._transport.get_clip + client._client._transport.get_event in client._client._transport._wrapped_methods ) @@ -7738,16 +7608,16 @@ async def test_get_clip_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_clip + client._client._transport.get_event ] = mock_rpc request = {} - await client.get_clip(request) + await client.get_event(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - await client.get_clip(request) + await client.get_event(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -7755,8 +7625,8 @@ async def test_get_clip_async_use_cached_wrapped_rpc(transport: str = "grpc_asyn @pytest.mark.asyncio -async def test_get_clip_async( - transport: str = "grpc_asyncio", request_type=service.GetClipRequest +async def test_get_event_async( + transport: str = "grpc_asyncio", request_type=service.GetEventRequest ): client = LivestreamServiceAsyncClient( credentials=async_anonymous_credentials(), @@ -7768,52 +7638,50 @@ async def test_get_clip_async( request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_clip), "__call__") as call: + 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.Clip( + resources.Event( name="name_value", - state=resources.Clip.State.PENDING, - output_uri="output_uri_value", - output_type=resources.Clip.OutputType.MANIFEST, + execute_now=True, + state=resources.Event.State.SCHEDULED, ) ) - response = await client.get_clip(request) + response = await client.get_event(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request = service.GetClipRequest() + request = service.GetEventRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, resources.Clip) + assert isinstance(response, resources.Event) 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 + assert response.execute_now is True + assert response.state == resources.Event.State.SCHEDULED @pytest.mark.asyncio -async def test_get_clip_async_from_dict(): - await test_get_clip_async(request_type=dict) +async def test_get_event_async_from_dict(): + await test_get_event_async(request_type=dict) -def test_get_clip_field_headers(): +def test_get_event_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.GetClipRequest() + request = service.GetEventRequest() request.name = "name_value" # Mock the actual call within the gRPC stub, 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) + with mock.patch.object(type(client.transport.get_event), "__call__") as call: + call.return_value = resources.Event() + client.get_event(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 @@ -7829,21 +7697,21 @@ def test_get_clip_field_headers(): @pytest.mark.asyncio -async def test_get_clip_field_headers_async(): +async def test_get_event_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.GetClipRequest() + request = service.GetEventRequest() request.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_clip), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.Clip()) - await client.get_clip(request) + with mock.patch.object(type(client.transport.get_event), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.Event()) + await client.get_event(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) @@ -7858,18 +7726,18 @@ async def test_get_clip_field_headers_async(): ) in kw["metadata"] -def test_get_clip_flattened(): +def test_get_event_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_clip), "__call__") as call: + with mock.patch.object(type(client.transport.get_event), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = resources.Clip() + call.return_value = resources.Event() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - client.get_clip( + client.get_event( name="name_value", ) @@ -7882,7 +7750,7 @@ def test_get_clip_flattened(): assert arg == mock_val -def test_get_clip_flattened_error(): +def test_get_event_flattened_error(): client = LivestreamServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -7890,27 +7758,27 @@ def test_get_clip_flattened_error(): # 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(), + client.get_event( + service.GetEventRequest(), name="name_value", ) @pytest.mark.asyncio -async def test_get_clip_flattened_async(): +async def test_get_event_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_clip), "__call__") as call: + with mock.patch.object(type(client.transport.get_event), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = resources.Clip() + call.return_value = resources.Event() - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.Clip()) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.Event()) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - response = await client.get_clip( + response = await client.get_event( name="name_value", ) @@ -7924,7 +7792,7 @@ async def test_get_clip_flattened_async(): @pytest.mark.asyncio -async def test_get_clip_flattened_error_async(): +async def test_get_event_flattened_error_async(): client = LivestreamServiceAsyncClient( credentials=async_anonymous_credentials(), ) @@ -7932,8 +7800,8 @@ async def test_get_clip_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_clip( - service.GetClipRequest(), + await client.get_event( + service.GetEventRequest(), name="name_value", ) @@ -7941,11 +7809,11 @@ async def test_get_clip_flattened_error_async(): @pytest.mark.parametrize( "request_type", [ - service.CreateClipRequest, + service.DeleteEventRequest, dict, ], ) -def test_create_clip(request_type, transport: str = "grpc"): +def test_delete_event(request_type, transport: str = "grpc"): client = LivestreamServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -7956,22 +7824,22 @@ def test_create_clip(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_clip), "__call__") as call: + with mock.patch.object(type(client.transport.delete_event), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name="operations/spam") - response = client.create_clip(request) + call.return_value = None + response = client.delete_event(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - request = service.CreateClipRequest() + request = service.DeleteEventRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) + assert response is None -def test_create_clip_non_empty_request_with_auto_populated_field(): +def test_delete_event_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. client = LivestreamServiceClient( @@ -7982,28 +7850,26 @@ def test_create_clip_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.CreateClipRequest( - parent="parent_value", - clip_id="clip_id_value", + request = service.DeleteEventRequest( + 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.create_clip), "__call__") as call: + with mock.patch.object(type(client.transport.delete_event), "__call__") as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.create_clip(request=request) + client.delete_event(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == service.CreateClipRequest( - parent="parent_value", - clip_id="clip_id_value", + assert args[0] == service.DeleteEventRequest( + name="name_value", request_id="request_id_value", ) -def test_create_clip_use_cached_wrapped_rpc(): +def test_delete_event_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -8017,26 +7883,21 @@ def test_create_clip_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.create_clip 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.create_clip] = mock_rpc + client._transport._wrapped_methods[client._transport.delete_event] = mock_rpc request = {} - client.create_clip(request) + client.delete_event(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - # Operation methods call wrapper_fn to build a cached - # client._transport.operations_client instance on first rpc call. - # Subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() - - client.create_clip(request) + client.delete_event(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -8044,7 +7905,7 @@ def test_create_clip_use_cached_wrapped_rpc(): @pytest.mark.asyncio -async def test_create_clip_async_use_cached_wrapped_rpc( +async def test_delete_event_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", ): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, @@ -8061,7 +7922,7 @@ async def test_create_clip_async_use_cached_wrapped_rpc( # Ensure method has been cached assert ( - client._client._transport.create_clip + client._client._transport.delete_event in client._client._transport._wrapped_methods ) @@ -8069,21 +7930,16 @@ async def test_create_clip_async_use_cached_wrapped_rpc( mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() client._client._transport._wrapped_methods[ - client._client._transport.create_clip + client._client._transport.delete_event ] = mock_rpc request = {} - await client.create_clip(request) + await client.delete_event(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - # Operation methods call wrapper_fn to build a cached - # client._transport.operations_client instance on first rpc call. - # Subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() - - await client.create_clip(request) + await client.delete_event(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -8091,8 +7947,8 @@ async def test_create_clip_async_use_cached_wrapped_rpc( @pytest.mark.asyncio -async def test_create_clip_async( - transport: str = "grpc_asyncio", request_type=service.CreateClipRequest +async def test_delete_event_async( + transport: str = "grpc_asyncio", request_type=service.DeleteEventRequest ): client = LivestreamServiceAsyncClient( credentials=async_anonymous_credentials(), @@ -8104,43 +7960,41 @@ async def test_create_clip_async( request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.create_clip), "__call__") as call: + 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( - operations_pb2.Operation(name="operations/spam") - ) - response = await client.create_clip(request) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_event(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request = service.CreateClipRequest() + request = service.DeleteEventRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) + assert response is None @pytest.mark.asyncio -async def test_create_clip_async_from_dict(): - await test_create_clip_async(request_type=dict) +async def test_delete_event_async_from_dict(): + await test_delete_event_async(request_type=dict) -def test_create_clip_field_headers(): +def test_delete_event_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.CreateClipRequest() + request = service.DeleteEventRequest() - request.parent = "parent_value" + request.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.create_clip), "__call__") as call: - call.return_value = operations_pb2.Operation(name="operations/op") - client.create_clip(request) + with mock.patch.object(type(client.transport.delete_event), "__call__") as call: + call.return_value = None + client.delete_event(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 @@ -8151,28 +8005,26 @@ def test_create_clip_field_headers(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "parent=parent_value", + "name=name_value", ) in kw["metadata"] @pytest.mark.asyncio -async def test_create_clip_field_headers_async(): +async def test_delete_event_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.CreateClipRequest() + request = service.DeleteEventRequest() - request.parent = "parent_value" + request.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.create_clip), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/op") - ) - await client.create_clip(request) + with mock.patch.object(type(client.transport.delete_event), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_event(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) @@ -8183,43 +8035,35 @@ async def test_create_clip_field_headers_async(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "parent=parent_value", + "name=name_value", ) in kw["metadata"] -def test_create_clip_flattened(): +def test_delete_event_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_clip), "__call__") as call: + with mock.patch.object(type(client.transport.delete_event), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name="operations/op") + call.return_value = None # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - client.create_clip( - parent="parent_value", - clip=resources.Clip(name="name_value"), - clip_id="clip_id_value", + client.delete_event( + name="name_value", ) # Establish that the underlying call was made with the expected # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - arg = args[0].parent - mock_val = "parent_value" - assert arg == mock_val - arg = args[0].clip - mock_val = resources.Clip(name="name_value") - assert arg == mock_val - arg = args[0].clip_id - mock_val = "clip_id_value" + arg = args[0].name + mock_val = "name_value" assert arg == mock_val -def test_create_clip_flattened_error(): +def test_delete_event_flattened_error(): client = LivestreamServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -8227,53 +8071,41 @@ def test_create_clip_flattened_error(): # 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.delete_event( + service.DeleteEventRequest(), + name="name_value", ) @pytest.mark.asyncio -async def test_create_clip_flattened_async(): +async def test_delete_event_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_clip), "__call__") as call: + with mock.patch.object(type(client.transport.delete_event), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name="operations/op") + call.return_value = None - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") - ) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - response = await client.create_clip( - parent="parent_value", - clip=resources.Clip(name="name_value"), - clip_id="clip_id_value", + response = await client.delete_event( + name="name_value", ) # Establish that the underlying call was made with the expected # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - arg = args[0].parent - mock_val = "parent_value" - assert arg == mock_val - arg = args[0].clip - mock_val = resources.Clip(name="name_value") - assert arg == mock_val - arg = args[0].clip_id - mock_val = "clip_id_value" + arg = args[0].name + mock_val = "name_value" assert arg == mock_val @pytest.mark.asyncio -async def test_create_clip_flattened_error_async(): +async def test_delete_event_flattened_error_async(): client = LivestreamServiceAsyncClient( credentials=async_anonymous_credentials(), ) @@ -8281,22 +8113,20 @@ async def test_create_clip_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_clip( - service.CreateClipRequest(), - parent="parent_value", - clip=resources.Clip(name="name_value"), - clip_id="clip_id_value", + await client.delete_event( + service.DeleteEventRequest(), + name="name_value", ) @pytest.mark.parametrize( "request_type", [ - service.DeleteClipRequest, + service.ListClipsRequest, dict, ], ) -def test_delete_clip(request_type, transport: str = "grpc"): +def test_list_clips(request_type, transport: str = "grpc"): client = LivestreamServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -8307,22 +8137,27 @@ def test_delete_clip(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_clip), "__call__") as call: + with mock.patch.object(type(client.transport.list_clips), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name="operations/spam") - response = client.delete_clip(request) + call.return_value = service.ListClipsResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], + ) + response = client.list_clips(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - request = service.DeleteClipRequest() + request = service.ListClipsRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) + assert isinstance(response, pagers.ListClipsPager) + assert response.next_page_token == "next_page_token_value" + assert response.unreachable == ["unreachable_value"] -def test_delete_clip_non_empty_request_with_auto_populated_field(): +def test_list_clips_non_empty_request_with_auto_populated_field(): # 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( @@ -8333,24 +8168,30 @@ def test_delete_clip_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.DeleteClipRequest( - name="name_value", + request = service.ListClipsRequest( + 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_clip), "__call__") as call: + with mock.patch.object(type(client.transport.list_clips), "__call__") as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.delete_clip(request=request) + client.list_clips(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == service.DeleteClipRequest( - name="name_value", + assert args[0] == service.ListClipsRequest( + parent="parent_value", + page_token="page_token_value", + filter="filter_value", + order_by="order_by_value", ) -def test_delete_clip_use_cached_wrapped_rpc(): +def test_list_clips_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -8364,26 +8205,21 @@ def test_delete_clip_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.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.delete_clip] = mock_rpc + client._transport._wrapped_methods[client._transport.list_clips] = mock_rpc request = {} - client.delete_clip(request) + client.list_clips(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_clip(request) + client.list_clips(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -8391,9 +8227,7 @@ def test_delete_clip_use_cached_wrapped_rpc(): @pytest.mark.asyncio -async def test_delete_clip_async_use_cached_wrapped_rpc( - transport: str = "grpc_asyncio", -): +async def test_list_clips_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: @@ -8408,7 +8242,7 @@ async def test_delete_clip_async_use_cached_wrapped_rpc( # Ensure method has been cached assert ( - client._client._transport.delete_clip + client._client._transport.list_clips in client._client._transport._wrapped_methods ) @@ -8416,21 +8250,16 @@ async def test_delete_clip_async_use_cached_wrapped_rpc( mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() client._client._transport._wrapped_methods[ - client._client._transport.delete_clip + client._client._transport.list_clips ] = mock_rpc request = {} - await client.delete_clip(request) + await client.list_clips(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_clip(request) + await client.list_clips(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -8438,8 +8267,8 @@ async def test_delete_clip_async_use_cached_wrapped_rpc( @pytest.mark.asyncio -async def test_delete_clip_async( - transport: str = "grpc_asyncio", request_type=service.DeleteClipRequest +async def test_list_clips_async( + transport: str = "grpc_asyncio", request_type=service.ListClipsRequest ): client = LivestreamServiceAsyncClient( credentials=async_anonymous_credentials(), @@ -8451,43 +8280,48 @@ async def test_delete_clip_async( request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.delete_clip), "__call__") as call: + 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( - operations_pb2.Operation(name="operations/spam") + service.ListClipsResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], + ) ) - response = await client.delete_clip(request) + response = await client.list_clips(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request = service.DeleteClipRequest() + request = service.ListClipsRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) + assert isinstance(response, pagers.ListClipsAsyncPager) + assert response.next_page_token == "next_page_token_value" + assert response.unreachable == ["unreachable_value"] @pytest.mark.asyncio -async def test_delete_clip_async_from_dict(): - await test_delete_clip_async(request_type=dict) +async def test_list_clips_async_from_dict(): + await test_list_clips_async(request_type=dict) -def test_delete_clip_field_headers(): +def test_list_clips_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.DeleteClipRequest() + request = service.ListClipsRequest() - 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_clip), "__call__") as call: - call.return_value = operations_pb2.Operation(name="operations/op") - client.delete_clip(request) + with mock.patch.object(type(client.transport.list_clips), "__call__") as call: + call.return_value = service.ListClipsResponse() + client.list_clips(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 @@ -8498,28 +8332,28 @@ def test_delete_clip_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_clip_field_headers_async(): +async def test_list_clips_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.DeleteClipRequest() + request = service.ListClipsRequest() - 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_clip), "__call__") as call: + with mock.patch.object(type(client.transport.list_clips), "__call__") as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/op") + service.ListClipsResponse() ) - await client.delete_clip(request) + await client.list_clips(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) @@ -8530,35 +8364,35 @@ async def test_delete_clip_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_clip_flattened(): +def test_list_clips_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_clip), "__call__") as call: + with mock.patch.object(type(client.transport.list_clips), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name="operations/op") + call.return_value = service.ListClipsResponse() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - client.delete_clip( - name="name_value", + client.list_clips( + 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_clip_flattened_error(): +def test_list_clips_flattened_error(): client = LivestreamServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -8566,43 +8400,43 @@ def test_delete_clip_flattened_error(): # 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", + client.list_clips( + service.ListClipsRequest(), + parent="parent_value", ) @pytest.mark.asyncio -async def test_delete_clip_flattened_async(): +async def test_list_clips_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_clip), "__call__") as call: + with mock.patch.object(type(client.transport.list_clips), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name="operations/op") + call.return_value = service.ListClipsResponse() call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") + service.ListClipsResponse() ) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - response = await client.delete_clip( - name="name_value", + response = await client.list_clips( + 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_clip_flattened_error_async(): +async def test_list_clips_flattened_error_async(): client = LivestreamServiceAsyncClient( credentials=async_anonymous_credentials(), ) @@ -8610,80 +8444,277 @@ async def test_delete_clip_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_clip( - service.DeleteClipRequest(), - name="name_value", + await client.list_clips( + service.ListClipsRequest(), + parent="parent_value", ) -@pytest.mark.parametrize( - "request_type", - [ - service.CreateDvrSessionRequest, - dict, - ], -) -def test_create_dvr_session(request_type, transport: str = "grpc"): +def test_list_clips_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.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_dvr_session(request) + with mock.patch.object(type(client.transport.list_clips), "__call__") as call: + # Set the response to a series of pages. + call.side_effect = ( + 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(), + ], + ), + RuntimeError, + ) - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = service.CreateDvrSessionRequest() - assert args[0] == request + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)), + ) + pager = client.list_clips(request={}, retry=retry, timeout=timeout) - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) + assert pager._metadata == expected_metadata + assert pager._retry == retry + assert pager._timeout == timeout + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, resources.Clip) for i in results) -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. +def test_list_clips_pages(transport_name: str = "grpc"): client = LivestreamServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", + transport=transport_name, ) - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = service.CreateDvrSessionRequest( - parent="parent_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.list_clips), "__call__") as call: + # Set the response to a series of pages. + call.side_effect = ( + 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(), + ], + ), + RuntimeError, + ) + pages = list(client.list_clips(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_clips_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.create_dvr_session), "__call__" + type(client.transport.list_clips), "__call__", new_callable=mock.AsyncMock + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + 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(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_clips( + 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.Clip) for i in responses) + + +@pytest.mark.asyncio +async def test_list_clips_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_clips), "__call__", new_callable=mock.AsyncMock ) as call: + # Set the response to a series of pages. + call.side_effect = ( + 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(), + ], + ), + 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_clips(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.GetClipRequest, + dict, + ], +) +def test_get_clip(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_clip), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = resources.Clip( + name="name_value", + state=resources.Clip.State.PENDING, + output_uri="output_uri_value", + output_type=resources.Clip.OutputType.MANIFEST, + ) + response = client.get_clip(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = service.GetClipRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + 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 + + +def test_get_clip_non_empty_request_with_auto_populated_field(): + # 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.GetClipRequest( + name="name_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_clip), "__call__") as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.create_dvr_session(request=request) + client.get_clip(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == service.CreateDvrSessionRequest( - parent="parent_value", - dvr_session_id="dvr_session_id_value", + assert args[0] == service.GetClipRequest( + name="name_value", ) -def test_create_dvr_session_use_cached_wrapped_rpc(): +def test_get_clip_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -8697,30 +8728,21 @@ def test_create_dvr_session_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert ( - client._transport.create_dvr_session in client._transport._wrapped_methods - ) + assert client._transport.get_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_dvr_session - ] = mock_rpc + client._transport._wrapped_methods[client._transport.get_clip] = mock_rpc request = {} - client.create_dvr_session(request) + client.get_clip(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - # Operation methods call wrapper_fn to build a cached - # client._transport.operations_client instance on first rpc call. - # Subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() - - client.create_dvr_session(request) + client.get_clip(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -8728,9 +8750,7 @@ def test_create_dvr_session_use_cached_wrapped_rpc(): @pytest.mark.asyncio -async def test_create_dvr_session_async_use_cached_wrapped_rpc( - transport: str = "grpc_asyncio", -): +async def test_get_clip_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: @@ -8745,7 +8765,7 @@ async def test_create_dvr_session_async_use_cached_wrapped_rpc( # Ensure method has been cached assert ( - client._client._transport.create_dvr_session + client._client._transport.get_clip in client._client._transport._wrapped_methods ) @@ -8753,21 +8773,16 @@ async def test_create_dvr_session_async_use_cached_wrapped_rpc( mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() client._client._transport._wrapped_methods[ - client._client._transport.create_dvr_session + client._client._transport.get_clip ] = mock_rpc request = {} - await client.create_dvr_session(request) + await client.get_clip(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - # Operation methods call wrapper_fn to build a cached - # client._transport.operations_client instance on first rpc call. - # Subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() - - await client.create_dvr_session(request) + await client.get_clip(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -8775,8 +8790,8 @@ async def test_create_dvr_session_async_use_cached_wrapped_rpc( @pytest.mark.asyncio -async def test_create_dvr_session_async( - transport: str = "grpc_asyncio", request_type=service.CreateDvrSessionRequest +async def test_get_clip_async( + transport: str = "grpc_asyncio", request_type=service.GetClipRequest ): client = LivestreamServiceAsyncClient( credentials=async_anonymous_credentials(), @@ -8788,47 +8803,52 @@ async def test_create_dvr_session_async( request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_dvr_session), "__call__" - ) as call: + 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( - operations_pb2.Operation(name="operations/spam") + resources.Clip( + name="name_value", + state=resources.Clip.State.PENDING, + output_uri="output_uri_value", + output_type=resources.Clip.OutputType.MANIFEST, + ) ) - response = await client.create_dvr_session(request) + response = await client.get_clip(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request = service.CreateDvrSessionRequest() + request = service.GetClipRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) + 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.asyncio -async def test_create_dvr_session_async_from_dict(): - await test_create_dvr_session_async(request_type=dict) +async def test_get_clip_async_from_dict(): + await test_get_clip_async(request_type=dict) -def test_create_dvr_session_field_headers(): +def test_get_clip_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.CreateDvrSessionRequest() + request = service.GetClipRequest() - request.parent = "parent_value" + request.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_dvr_session), "__call__" - ) as call: - call.return_value = operations_pb2.Operation(name="operations/op") - client.create_dvr_session(request) + with mock.patch.object(type(client.transport.get_clip), "__call__") as call: + call.return_value = resources.Clip() + client.get_clip(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 @@ -8839,30 +8859,26 @@ def test_create_dvr_session_field_headers(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "parent=parent_value", + "name=name_value", ) in kw["metadata"] @pytest.mark.asyncio -async def test_create_dvr_session_field_headers_async(): +async def test_get_clip_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.CreateDvrSessionRequest() + request = service.GetClipRequest() - request.parent = "parent_value" + request.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_dvr_session), "__call__" - ) as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/op") - ) - await client.create_dvr_session(request) + with mock.patch.object(type(client.transport.get_clip), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.Clip()) + await client.get_clip(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) @@ -8873,45 +8889,35 @@ async def test_create_dvr_session_field_headers_async(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "parent=parent_value", + "name=name_value", ) in kw["metadata"] -def test_create_dvr_session_flattened(): +def test_get_clip_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_dvr_session), "__call__" - ) as call: + with mock.patch.object(type(client.transport.get_clip), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name="operations/op") + call.return_value = resources.Clip() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - client.create_dvr_session( - parent="parent_value", - dvr_session=resources.DvrSession(name="name_value"), - dvr_session_id="dvr_session_id_value", + client.get_clip( + name="name_value", ) # Establish that the underlying call was made with the expected # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - arg = args[0].parent - mock_val = "parent_value" - assert arg == mock_val - arg = args[0].dvr_session - mock_val = resources.DvrSession(name="name_value") - assert arg == mock_val - arg = args[0].dvr_session_id - mock_val = "dvr_session_id_value" + arg = args[0].name + mock_val = "name_value" assert arg == mock_val -def test_create_dvr_session_flattened_error(): +def test_get_clip_flattened_error(): client = LivestreamServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -8919,55 +8925,41 @@ def test_create_dvr_session_flattened_error(): # 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", + client.get_clip( + service.GetClipRequest(), + name="name_value", ) @pytest.mark.asyncio -async def test_create_dvr_session_flattened_async(): +async def test_get_clip_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_dvr_session), "__call__" - ) as call: + with mock.patch.object(type(client.transport.get_clip), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name="operations/op") + call.return_value = resources.Clip() - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") - ) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.Clip()) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - response = await client.create_dvr_session( - parent="parent_value", - dvr_session=resources.DvrSession(name="name_value"), - dvr_session_id="dvr_session_id_value", + response = await client.get_clip( + name="name_value", ) # Establish that the underlying call was made with the expected # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - arg = args[0].parent - mock_val = "parent_value" - assert arg == mock_val - arg = args[0].dvr_session - mock_val = resources.DvrSession(name="name_value") - assert arg == mock_val - arg = args[0].dvr_session_id - mock_val = "dvr_session_id_value" + arg = args[0].name + mock_val = "name_value" assert arg == mock_val @pytest.mark.asyncio -async def test_create_dvr_session_flattened_error_async(): +async def test_get_clip_flattened_error_async(): client = LivestreamServiceAsyncClient( credentials=async_anonymous_credentials(), ) @@ -8975,22 +8967,20 @@ async def test_create_dvr_session_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_dvr_session( - service.CreateDvrSessionRequest(), - parent="parent_value", - dvr_session=resources.DvrSession(name="name_value"), - dvr_session_id="dvr_session_id_value", + await client.get_clip( + service.GetClipRequest(), + name="name_value", ) @pytest.mark.parametrize( "request_type", [ - service.ListDvrSessionsRequest, + service.CreateClipRequest, dict, ], ) -def test_list_dvr_sessions(request_type, transport: str = "grpc"): +def test_create_clip(request_type, transport: str = "grpc"): client = LivestreamServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -9001,29 +8991,22 @@ def test_list_dvr_sessions(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_dvr_sessions), "__call__" - ) as call: + with mock.patch.object(type(client.transport.create_clip), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = service.ListDvrSessionsResponse( - next_page_token="next_page_token_value", - unreachable=["unreachable_value"], - ) - response = client.list_dvr_sessions(request) + call.return_value = operations_pb2.Operation(name="operations/spam") + response = client.create_clip(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - request = service.ListDvrSessionsRequest() + request = service.CreateClipRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListDvrSessionsPager) - assert response.next_page_token == "next_page_token_value" - assert response.unreachable == ["unreachable_value"] + assert isinstance(response, future.Future) -def test_list_dvr_sessions_non_empty_request_with_auto_populated_field(): +def test_create_clip_non_empty_request_with_auto_populated_field(): # 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( @@ -9034,32 +9017,28 @@ def test_list_dvr_sessions_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.ListDvrSessionsRequest( + request = service.CreateClipRequest( parent="parent_value", - page_token="page_token_value", - filter="filter_value", - order_by="order_by_value", + clip_id="clip_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.list_dvr_sessions), "__call__" - ) as call: + with mock.patch.object(type(client.transport.create_clip), "__call__") as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.list_dvr_sessions(request=request) + client.create_clip(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == service.ListDvrSessionsRequest( + assert args[0] == service.CreateClipRequest( parent="parent_value", - page_token="page_token_value", - filter="filter_value", - order_by="order_by_value", + clip_id="clip_id_value", + request_id="request_id_value", ) -def test_list_dvr_sessions_use_cached_wrapped_rpc(): +def test_create_clip_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -9073,23 +9052,26 @@ def test_list_dvr_sessions_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.list_dvr_sessions in client._transport._wrapped_methods + 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.list_dvr_sessions - ] = mock_rpc + client._transport._wrapped_methods[client._transport.create_clip] = mock_rpc request = {} - client.list_dvr_sessions(request) + client.create_clip(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.list_dvr_sessions(request) + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.create_clip(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -9097,7 +9079,7 @@ def test_list_dvr_sessions_use_cached_wrapped_rpc(): @pytest.mark.asyncio -async def test_list_dvr_sessions_async_use_cached_wrapped_rpc( +async def test_create_clip_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", ): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, @@ -9114,7 +9096,7 @@ async def test_list_dvr_sessions_async_use_cached_wrapped_rpc( # Ensure method has been cached assert ( - client._client._transport.list_dvr_sessions + client._client._transport.create_clip in client._client._transport._wrapped_methods ) @@ -9122,16 +9104,21 @@ async def test_list_dvr_sessions_async_use_cached_wrapped_rpc( mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() client._client._transport._wrapped_methods[ - client._client._transport.list_dvr_sessions + client._client._transport.create_clip ] = mock_rpc request = {} - await client.list_dvr_sessions(request) + await client.create_clip(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - await client.list_dvr_sessions(request) + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.create_clip(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -9139,8 +9126,8 @@ async def test_list_dvr_sessions_async_use_cached_wrapped_rpc( @pytest.mark.asyncio -async def test_list_dvr_sessions_async( - transport: str = "grpc_asyncio", request_type=service.ListDvrSessionsRequest +async def test_create_clip_async( + transport: str = "grpc_asyncio", request_type=service.CreateClipRequest ): client = LivestreamServiceAsyncClient( credentials=async_anonymous_credentials(), @@ -9152,52 +9139,43 @@ async def test_list_dvr_sessions_async( request = request_type() # 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: + 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( - service.ListDvrSessionsResponse( - next_page_token="next_page_token_value", - unreachable=["unreachable_value"], - ) + operations_pb2.Operation(name="operations/spam") ) - response = await client.list_dvr_sessions(request) + response = await client.create_clip(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request = service.ListDvrSessionsRequest() + request = service.CreateClipRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListDvrSessionsAsyncPager) - 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_dvr_sessions_async_from_dict(): - await test_list_dvr_sessions_async(request_type=dict) +async def test_create_clip_async_from_dict(): + await test_create_clip_async(request_type=dict) -def test_list_dvr_sessions_field_headers(): +def test_create_clip_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.ListDvrSessionsRequest() + request = service.CreateClipRequest() request.parent = "parent_value" # 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: - call.return_value = service.ListDvrSessionsResponse() - client.list_dvr_sessions(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) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 @@ -9213,25 +9191,23 @@ def test_list_dvr_sessions_field_headers(): @pytest.mark.asyncio -async def test_list_dvr_sessions_field_headers_async(): +async def test_create_clip_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.ListDvrSessionsRequest() + request = service.CreateClipRequest() request.parent = "parent_value" # 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: + with mock.patch.object(type(client.transport.create_clip), "__call__") as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - service.ListDvrSessionsResponse() + operations_pb2.Operation(name="operations/op") ) - await client.list_dvr_sessions(request) + await client.create_clip(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) @@ -9246,21 +9222,21 @@ async def test_list_dvr_sessions_field_headers_async(): ) in kw["metadata"] -def test_list_dvr_sessions_flattened(): +def test_create_clip_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_dvr_sessions), "__call__" - ) as call: + with mock.patch.object(type(client.transport.create_clip), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = service.ListDvrSessionsResponse() + 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_dvr_sessions( + client.create_clip( parent="parent_value", + clip=resources.Clip(name="name_value"), + clip_id="clip_id_value", ) # Establish that the underlying call was made with the expected @@ -9270,42 +9246,50 @@ def test_list_dvr_sessions_flattened(): arg = args[0].parent mock_val = "parent_value" assert arg == mock_val - - -def test_list_dvr_sessions_flattened_error(): - client = LivestreamServiceClient( + arg = args[0].clip + mock_val = resources.Clip(name="name_value") + assert arg == mock_val + arg = args[0].clip_id + mock_val = "clip_id_value" + assert arg == mock_val + + +def test_create_clip_flattened_error(): + client = LivestreamServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.list_dvr_sessions( - service.ListDvrSessionsRequest(), + client.create_clip( + service.CreateClipRequest(), parent="parent_value", + clip=resources.Clip(name="name_value"), + clip_id="clip_id_value", ) @pytest.mark.asyncio -async def test_list_dvr_sessions_flattened_async(): +async def test_create_clip_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_dvr_sessions), "__call__" - ) as call: + with mock.patch.object(type(client.transport.create_clip), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = service.ListDvrSessionsResponse() + call.return_value = operations_pb2.Operation(name="operations/op") call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - service.ListDvrSessionsResponse() + 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_dvr_sessions( + response = await client.create_clip( parent="parent_value", + clip=resources.Clip(name="name_value"), + clip_id="clip_id_value", ) # Establish that the underlying call was made with the expected @@ -9315,10 +9299,16 @@ async def test_list_dvr_sessions_flattened_async(): arg = args[0].parent mock_val = "parent_value" assert arg == mock_val + arg = args[0].clip + mock_val = resources.Clip(name="name_value") + assert arg == mock_val + arg = args[0].clip_id + mock_val = "clip_id_value" + assert arg == mock_val @pytest.mark.asyncio -async def test_list_dvr_sessions_flattened_error_async(): +async def test_create_clip_flattened_error_async(): client = LivestreamServiceAsyncClient( credentials=async_anonymous_credentials(), ) @@ -9326,309 +9316,109 @@ async def test_list_dvr_sessions_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_dvr_sessions( - service.ListDvrSessionsRequest(), + await client.create_clip( + service.CreateClipRequest(), parent="parent_value", + clip=resources.Clip(name="name_value"), + clip_id="clip_id_value", ) -def test_list_dvr_sessions_pager(transport_name: str = "grpc"): +@pytest.mark.parametrize( + "request_type", + [ + service.DeleteClipRequest, + dict, + ], +) +def test_delete_clip(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_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, - ) + # Everything is optional in proto3 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_dvr_sessions(request={}, retry=retry, timeout=timeout) + # Mock the actual call within the gRPC stub, 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 = operations_pb2.Operation(name="operations/spam") + response = client.delete_clip(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.DeleteClipRequest() + assert args[0] == request - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, resources.DvrSession) for i in results) + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) -def test_list_dvr_sessions_pages(transport_name: str = "grpc"): +def test_delete_clip_non_empty_request_with_auto_populated_field(): + # 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", + ) + + # Populate all string fields in the 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.DeleteClipRequest( + name="name_value", ) # 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, + with mock.patch.object(type(client.transport.delete_clip), "__call__") as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.delete_clip(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == service.DeleteClipRequest( + name="name_value", ) - 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, +def test_delete_clip_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached 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", ) - async_pager = await client.list_dvr_sessions( - request={}, + + # Should 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_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. ) - assert async_pager.next_page_token == "abc" - responses = [] - async for response in async_pager: # pragma: no branch - responses.append(response) + client._transport._wrapped_methods[client._transport.delete_clip] = mock_rpc + request = {} + client.delete_clip(request) - assert len(responses) == 6 - assert all(isinstance(i, resources.DvrSession) for i in responses) + # 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() -@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( - 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.GetDvrSessionRequest( - name="name_value", - ) - - # 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: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.get_dvr_session(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == service.GetDvrSessionRequest( - name="name_value", - ) - - -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: - 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() - - # 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 - 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) + client.delete_clip(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -9636,7 +9426,7 @@ def test_get_dvr_session_use_cached_wrapped_rpc(): @pytest.mark.asyncio -async def test_get_dvr_session_async_use_cached_wrapped_rpc( +async def test_delete_clip_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", ): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, @@ -9653,7 +9443,7 @@ async def test_get_dvr_session_async_use_cached_wrapped_rpc( # Ensure method has been cached assert ( - client._client._transport.get_dvr_session + client._client._transport.delete_clip in client._client._transport._wrapped_methods ) @@ -9661,16 +9451,21 @@ async def test_get_dvr_session_async_use_cached_wrapped_rpc( mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() client._client._transport._wrapped_methods[ - client._client._transport.get_dvr_session + client._client._transport.delete_clip ] = mock_rpc request = {} - await client.get_dvr_session(request) + await client.delete_clip(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - await client.get_dvr_session(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_clip(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -9678,8 +9473,8 @@ async def test_get_dvr_session_async_use_cached_wrapped_rpc( @pytest.mark.asyncio -async def test_get_dvr_session_async( - transport: str = "grpc_asyncio", request_type=service.GetDvrSessionRequest +async def test_delete_clip_async( + transport: str = "grpc_asyncio", request_type=service.DeleteClipRequest ): client = LivestreamServiceAsyncClient( credentials=async_anonymous_credentials(), @@ -9691,48 +9486,43 @@ async def test_get_dvr_session_async( 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: + 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( - resources.DvrSession( - name="name_value", - state=resources.DvrSession.State.PENDING, - ) + operations_pb2.Operation(name="operations/spam") ) - response = await client.get_dvr_session(request) + response = await client.delete_clip(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request = service.GetDvrSessionRequest() + request = service.DeleteClipRequest() 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 + assert isinstance(response, future.Future) @pytest.mark.asyncio -async def test_get_dvr_session_async_from_dict(): - await test_get_dvr_session_async(request_type=dict) +async def test_delete_clip_async_from_dict(): + await test_delete_clip_async(request_type=dict) -def test_get_dvr_session_field_headers(): +def test_delete_clip_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.GetDvrSessionRequest() + request = service.DeleteClipRequest() request.name = "name_value" # 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: - call.return_value = resources.DvrSession() - client.get_dvr_session(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) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 @@ -9748,23 +9538,23 @@ def test_get_dvr_session_field_headers(): @pytest.mark.asyncio -async def test_get_dvr_session_field_headers_async(): +async def test_delete_clip_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.GetDvrSessionRequest() + request = service.DeleteClipRequest() request.name = "name_value" # 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: + with mock.patch.object(type(client.transport.delete_clip), "__call__") as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - resources.DvrSession() + operations_pb2.Operation(name="operations/op") ) - await client.get_dvr_session(request) + await client.delete_clip(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) @@ -9779,18 +9569,18 @@ async def test_get_dvr_session_field_headers_async(): ) in kw["metadata"] -def test_get_dvr_session_flattened(): +def test_delete_clip_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_dvr_session), "__call__") as call: + with mock.patch.object(type(client.transport.delete_clip), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = resources.DvrSession() + 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_dvr_session( + client.delete_clip( name="name_value", ) @@ -9803,7 +9593,7 @@ def test_get_dvr_session_flattened(): assert arg == mock_val -def test_get_dvr_session_flattened_error(): +def test_delete_clip_flattened_error(): client = LivestreamServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -9811,29 +9601,29 @@ def test_get_dvr_session_flattened_error(): # 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(), + client.delete_clip( + service.DeleteClipRequest(), name="name_value", ) @pytest.mark.asyncio -async def test_get_dvr_session_flattened_async(): +async def test_delete_clip_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_dvr_session), "__call__") as call: + with mock.patch.object(type(client.transport.delete_clip), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = resources.DvrSession() + call.return_value = operations_pb2.Operation(name="operations/op") call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - resources.DvrSession() + 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_dvr_session( + response = await client.delete_clip( name="name_value", ) @@ -9847,7 +9637,7 @@ async def test_get_dvr_session_flattened_async(): @pytest.mark.asyncio -async def test_get_dvr_session_flattened_error_async(): +async def test_delete_clip_flattened_error_async(): client = LivestreamServiceAsyncClient( credentials=async_anonymous_credentials(), ) @@ -9855,8 +9645,8 @@ async def test_get_dvr_session_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_dvr_session( - service.GetDvrSessionRequest(), + await client.delete_clip( + service.DeleteClipRequest(), name="name_value", ) @@ -9864,11 +9654,11 @@ async def test_get_dvr_session_flattened_error_async(): @pytest.mark.parametrize( "request_type", [ - service.DeleteDvrSessionRequest, + service.CreateDvrSessionRequest, dict, ], ) -def test_delete_dvr_session(request_type, transport: str = "grpc"): +def test_create_dvr_session(request_type, transport: str = "grpc"): client = LivestreamServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -9880,23 +9670,23 @@ def test_delete_dvr_session(request_type, transport: str = "grpc"): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.delete_dvr_session), "__call__" + 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.delete_dvr_session(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.DeleteDvrSessionRequest() + request = service.CreateDvrSessionRequest() assert args[0] == request # Establish that the response is the type that we expect. assert isinstance(response, future.Future) -def test_delete_dvr_session_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( @@ -9907,26 +9697,28 @@ def test_delete_dvr_session_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.DeleteDvrSessionRequest( - name="name_value", + request = service.CreateDvrSessionRequest( + parent="parent_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.delete_dvr_session), "__call__" + 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.delete_dvr_session(request=request) + client.create_dvr_session(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == service.DeleteDvrSessionRequest( - name="name_value", + assert args[0] == service.CreateDvrSessionRequest( + parent="parent_value", + dvr_session_id="dvr_session_id_value", ) -def test_delete_dvr_session_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: @@ -9941,7 +9733,7 @@ def test_delete_dvr_session_use_cached_wrapped_rpc(): # Ensure method has been cached assert ( - client._transport.delete_dvr_session in client._transport._wrapped_methods + client._transport.create_dvr_session in client._transport._wrapped_methods ) # Replace cached wrapped function with mock @@ -9950,10 +9742,10 @@ def test_delete_dvr_session_use_cached_wrapped_rpc(): "foo" # operation_request.operation in compute client(s) expect a string. ) client._transport._wrapped_methods[ - client._transport.delete_dvr_session + client._transport.create_dvr_session ] = mock_rpc request = {} - client.delete_dvr_session(request) + client.create_dvr_session(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 @@ -9963,7 +9755,7 @@ def test_delete_dvr_session_use_cached_wrapped_rpc(): # Subsequent calls should use the cached wrapper wrapper_fn.reset_mock() - client.delete_dvr_session(request) + client.create_dvr_session(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -9971,7 +9763,7 @@ def test_delete_dvr_session_use_cached_wrapped_rpc(): @pytest.mark.asyncio -async def test_delete_dvr_session_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, @@ -9988,7 +9780,7 @@ async def test_delete_dvr_session_async_use_cached_wrapped_rpc( # Ensure method has been cached assert ( - client._client._transport.delete_dvr_session + client._client._transport.create_dvr_session in client._client._transport._wrapped_methods ) @@ -9996,11 +9788,11 @@ async def test_delete_dvr_session_async_use_cached_wrapped_rpc( mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() client._client._transport._wrapped_methods[ - client._client._transport.delete_dvr_session + client._client._transport.create_dvr_session ] = mock_rpc request = {} - await client.delete_dvr_session(request) + await client.create_dvr_session(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 @@ -10010,7 +9802,7 @@ async def test_delete_dvr_session_async_use_cached_wrapped_rpc( # Subsequent calls should use the cached wrapper wrapper_fn.reset_mock() - await client.delete_dvr_session(request) + await client.create_dvr_session(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -10018,8 +9810,8 @@ async def test_delete_dvr_session_async_use_cached_wrapped_rpc( @pytest.mark.asyncio -async def test_delete_dvr_session_async( - transport: str = "grpc_asyncio", request_type=service.DeleteDvrSessionRequest +async def test_create_dvr_session_async( + transport: str = "grpc_asyncio", request_type=service.CreateDvrSessionRequest ): client = LivestreamServiceAsyncClient( credentials=async_anonymous_credentials(), @@ -10032,18 +9824,18 @@ async def test_delete_dvr_session_async( # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.delete_dvr_session), "__call__" + 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.delete_dvr_session(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.DeleteDvrSessionRequest() + request = service.CreateDvrSessionRequest() assert args[0] == request # Establish that the response is the type that we expect. @@ -10051,27 +9843,27 @@ async def test_delete_dvr_session_async( @pytest.mark.asyncio -async def test_delete_dvr_session_async_from_dict(): - await test_delete_dvr_session_async(request_type=dict) +async def test_create_dvr_session_async_from_dict(): + await test_create_dvr_session_async(request_type=dict) -def test_delete_dvr_session_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.DeleteDvrSessionRequest() + request = service.CreateDvrSessionRequest() - 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_dvr_session), "__call__" + type(client.transport.create_dvr_session), "__call__" ) as call: call.return_value = operations_pb2.Operation(name="operations/op") - client.delete_dvr_session(request) + client.create_dvr_session(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 @@ -10082,30 +9874,30 @@ def test_delete_dvr_session_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_dvr_session_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.DeleteDvrSessionRequest() + request = service.CreateDvrSessionRequest() - 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_dvr_session), "__call__" + type(client.transport.create_dvr_session), "__call__" ) as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( operations_pb2.Operation(name="operations/op") ) - await client.delete_dvr_session(request) + await client.create_dvr_session(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) @@ -10116,37 +9908,45 @@ async def test_delete_dvr_session_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_dvr_session_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.delete_dvr_session), "__call__" + 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.delete_dvr_session( - name="name_value", + client.create_dvr_session( + parent="parent_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 # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = "name_value" + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + arg = args[0].dvr_session + mock_val = resources.DvrSession(name="name_value") + assert arg == mock_val + arg = args[0].dvr_session_id + mock_val = "dvr_session_id_value" assert arg == mock_val -def test_delete_dvr_session_flattened_error(): +def test_create_dvr_session_flattened_error(): client = LivestreamServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -10154,21 +9954,23 @@ def test_delete_dvr_session_flattened_error(): # 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", + client.create_dvr_session( + service.CreateDvrSessionRequest(), + parent="parent_value", + dvr_session=resources.DvrSession(name="name_value"), + dvr_session_id="dvr_session_id_value", ) @pytest.mark.asyncio -async def test_delete_dvr_session_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.delete_dvr_session), "__call__" + 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") @@ -10178,21 +9980,29 @@ async def test_delete_dvr_session_flattened_async(): ) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - response = await client.delete_dvr_session( - name="name_value", + response = await client.create_dvr_session( + parent="parent_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 # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = "name_value" + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + arg = args[0].dvr_session + mock_val = resources.DvrSession(name="name_value") + assert arg == mock_val + arg = args[0].dvr_session_id + mock_val = "dvr_session_id_value" assert arg == mock_val @pytest.mark.asyncio -async def test_delete_dvr_session_flattened_error_async(): +async def test_create_dvr_session_flattened_error_async(): client = LivestreamServiceAsyncClient( credentials=async_anonymous_credentials(), ) @@ -10200,20 +10010,22 @@ async def test_delete_dvr_session_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_dvr_session( - service.DeleteDvrSessionRequest(), - name="name_value", + await client.create_dvr_session( + service.CreateDvrSessionRequest(), + parent="parent_value", + dvr_session=resources.DvrSession(name="name_value"), + dvr_session_id="dvr_session_id_value", ) @pytest.mark.parametrize( "request_type", [ - service.UpdateDvrSessionRequest, + service.ListDvrSessionsRequest, dict, ], ) -def test_update_dvr_session(request_type, transport: str = "grpc"): +def test_list_dvr_sessions(request_type, transport: str = "grpc"): client = LivestreamServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -10225,23 +10037,28 @@ def test_update_dvr_session(request_type, transport: str = "grpc"): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_dvr_session), "__call__" + 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.update_dvr_session(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.UpdateDvrSessionRequest() + 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_update_dvr_session_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( @@ -10252,22 +10069,32 @@ def test_update_dvr_session_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.UpdateDvrSessionRequest() + 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.update_dvr_session), "__call__" + 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.update_dvr_session(request=request) + client.list_dvr_sessions(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == service.UpdateDvrSessionRequest() + assert args[0] == service.ListDvrSessionsRequest( + parent="parent_value", + page_token="page_token_value", + filter="filter_value", + order_by="order_by_value", + ) -def test_update_dvr_session_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: @@ -10281,9 +10108,7 @@ def test_update_dvr_session_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert ( - client._transport.update_dvr_session 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() @@ -10291,20 +10116,15 @@ def test_update_dvr_session_use_cached_wrapped_rpc(): "foo" # operation_request.operation in compute client(s) expect a string. ) client._transport._wrapped_methods[ - client._transport.update_dvr_session + client._transport.list_dvr_sessions ] = mock_rpc request = {} - client.update_dvr_session(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.update_dvr_session(request) + client.list_dvr_sessions(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -10312,7 +10132,7 @@ def test_update_dvr_session_use_cached_wrapped_rpc(): @pytest.mark.asyncio -async def test_update_dvr_session_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, @@ -10329,7 +10149,7 @@ async def test_update_dvr_session_async_use_cached_wrapped_rpc( # Ensure method has been cached assert ( - client._client._transport.update_dvr_session + client._client._transport.list_dvr_sessions in client._client._transport._wrapped_methods ) @@ -10337,21 +10157,16 @@ async def test_update_dvr_session_async_use_cached_wrapped_rpc( mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() client._client._transport._wrapped_methods[ - client._client._transport.update_dvr_session + client._client._transport.list_dvr_sessions ] = mock_rpc request = {} - await client.update_dvr_session(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.update_dvr_session(request) + await client.list_dvr_sessions(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -10359,8 +10174,8 @@ async def test_update_dvr_session_async_use_cached_wrapped_rpc( @pytest.mark.asyncio -async def test_update_dvr_session_async( - transport: str = "grpc_asyncio", request_type=service.UpdateDvrSessionRequest +async def test_list_dvr_sessions_async( + transport: str = "grpc_asyncio", request_type=service.ListDvrSessionsRequest ): client = LivestreamServiceAsyncClient( credentials=async_anonymous_credentials(), @@ -10373,46 +10188,51 @@ async def test_update_dvr_session_async( # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_dvr_session), "__call__" + 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.update_dvr_session(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.UpdateDvrSessionRequest() + 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_update_dvr_session_async_from_dict(): - await test_update_dvr_session_async(request_type=dict) +async def test_list_dvr_sessions_async_from_dict(): + await test_list_dvr_sessions_async(request_type=dict) -def test_update_dvr_session_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.UpdateDvrSessionRequest() + request = service.ListDvrSessionsRequest() - request.dvr_session.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_dvr_session), "__call__" + type(client.transport.list_dvr_sessions), "__call__" ) as call: - call.return_value = operations_pb2.Operation(name="operations/op") - client.update_dvr_session(request) + 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 @@ -10423,30 +10243,30 @@ def test_update_dvr_session_field_headers(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "dvr_session.name=name_value", + "parent=parent_value", ) in kw["metadata"] @pytest.mark.asyncio -async def test_update_dvr_session_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.UpdateDvrSessionRequest() + request = service.ListDvrSessionsRequest() - request.dvr_session.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_dvr_session), "__call__" + 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.update_dvr_session(request) + await client.list_dvr_sessions(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) @@ -10457,41 +10277,37 @@ async def test_update_dvr_session_field_headers_async(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "dvr_session.name=name_value", + "parent=parent_value", ) in kw["metadata"] -def test_update_dvr_session_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.update_dvr_session), "__call__" + 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.update_dvr_session( - dvr_session=resources.DvrSession(name="name_value"), - update_mask=field_mask_pb2.FieldMask(paths=["paths_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].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"]) + arg = args[0].parent + mock_val = "parent_value" assert arg == mock_val -def test_update_dvr_session_flattened_error(): +def test_list_dvr_sessions_flattened_error(): client = LivestreamServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -10499,50 +10315,45 @@ def test_update_dvr_session_flattened_error(): # 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"]), + client.list_dvr_sessions( + service.ListDvrSessionsRequest(), + parent="parent_value", ) @pytest.mark.asyncio -async def test_update_dvr_session_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.update_dvr_session), "__call__" + 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.update_dvr_session( - dvr_session=resources.DvrSession(name="name_value"), - update_mask=field_mask_pb2.FieldMask(paths=["paths_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].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"]) + arg = args[0].parent + mock_val = "parent_value" assert arg == mock_val @pytest.mark.asyncio -async def test_update_dvr_session_flattened_error_async(): +async def test_list_dvr_sessions_flattened_error_async(): client = LivestreamServiceAsyncClient( credentials=async_anonymous_credentials(), ) @@ -10550,21 +10361,222 @@ async def test_update_dvr_session_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_dvr_session( - service.UpdateDvrSessionRequest(), - dvr_session=resources.DvrSession(name="name_value"), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + await client.list_dvr_sessions( + service.ListDvrSessionsRequest(), + parent="parent_value", + ) + + +def test_list_dvr_sessions_pager(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, + ) + + 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 + + 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.CreateAssetRequest, + service.GetDvrSessionRequest, dict, ], ) -def test_create_asset(request_type, transport: str = "grpc"): +def test_get_dvr_session(request_type, transport: str = "grpc"): client = LivestreamServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -10575,22 +10587,27 @@ 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.get_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) + 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.CreateAssetRequest() + request = service.GetDvrSessionRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) + assert isinstance(response, resources.DvrSession) + assert response.name == "name_value" + assert response.state == resources.DvrSession.State.PENDING -def test_create_asset_non_empty_request_with_auto_populated_field(): +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( @@ -10601,28 +10618,24 @@ 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( - parent="parent_value", - asset_id="asset_id_value", - request_id="request_id_value", + 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.create_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.create_asset(request=request) + client.get_dvr_session(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == service.CreateAssetRequest( - parent="parent_value", - asset_id="asset_id_value", - request_id="request_id_value", + assert args[0] == service.GetDvrSessionRequest( + name="name_value", ) -def test_create_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: @@ -10636,26 +10649,21 @@ 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.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.create_asset] = mock_rpc + client._transport._wrapped_methods[client._transport.get_dvr_session] = mock_rpc request = {} - client.create_asset(request) + client.get_dvr_session(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - # Operation methods call wrapper_fn to build a cached - # client._transport.operations_client instance on first rpc call. - # Subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() - - client.create_asset(request) + client.get_dvr_session(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -10663,7 +10671,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_get_dvr_session_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", ): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, @@ -10680,7 +10688,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.get_dvr_session in client._client._transport._wrapped_methods ) @@ -10688,21 +10696,16 @@ 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.get_dvr_session ] = mock_rpc request = {} - await client.create_asset(request) + await client.get_dvr_session(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - # Operation methods call wrapper_fn to build a cached - # client._transport.operations_client instance on first rpc call. - # Subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() - - await client.create_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 @@ -10710,8 +10713,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_get_dvr_session_async( + transport: str = "grpc_asyncio", request_type=service.GetDvrSessionRequest ): client = LivestreamServiceAsyncClient( credentials=async_anonymous_credentials(), @@ -10723,43 +10726,48 @@ 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.get_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") + resources.DvrSession( + name="name_value", + state=resources.DvrSession.State.PENDING, + ) ) - response = await client.create_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.CreateAssetRequest() + request = service.GetDvrSessionRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) + assert isinstance(response, resources.DvrSession) + assert response.name == "name_value" + assert response.state == resources.DvrSession.State.PENDING @pytest.mark.asyncio -async def test_create_asset_async_from_dict(): - await test_create_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_create_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.CreateAssetRequest() + request = service.GetDvrSessionRequest() - request.parent = "parent_value" + request.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.create_asset), "__call__") as call: - call.return_value = operations_pb2.Operation(name="operations/op") - client.create_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 @@ -10770,28 +10778,28 @@ def test_create_asset_field_headers(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "parent=parent_value", + "name=name_value", ) in kw["metadata"] @pytest.mark.asyncio -async def test_create_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.CreateAssetRequest() + request = service.GetDvrSessionRequest() - request.parent = "parent_value" + request.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.create_asset), "__call__") as call: + with mock.patch.object(type(client.transport.get_dvr_session), "__call__") as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/op") + resources.DvrSession() ) - await client.create_asset(request) + await client.get_dvr_session(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) @@ -10802,43 +10810,35 @@ async def test_create_asset_field_headers_async(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "parent=parent_value", + "name=name_value", ) in kw["metadata"] -def test_create_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.create_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 = operations_pb2.Operation(name="operations/op") + call.return_value = resources.DvrSession() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - client.create_asset( - parent="parent_value", - asset=resources.Asset(name="name_value"), - asset_id="asset_id_value", + client.get_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" - assert arg == mock_val - 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" + arg = args[0].name + mock_val = "name_value" assert arg == mock_val -def test_create_asset_flattened_error(): +def test_get_dvr_session_flattened_error(): client = LivestreamServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -10846,53 +10846,43 @@ 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(), - parent="parent_value", - asset=resources.Asset(name="name_value"), - asset_id="asset_id_value", + client.get_dvr_session( + service.GetDvrSessionRequest(), + name="name_value", ) @pytest.mark.asyncio -async def test_create_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.create_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 = operations_pb2.Operation(name="operations/op") + call.return_value = resources.DvrSession() call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") + resources.DvrSession() ) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - response = await client.create_asset( - parent="parent_value", - asset=resources.Asset(name="name_value"), - asset_id="asset_id_value", + response = await client.get_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" - assert arg == mock_val - 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" + arg = args[0].name + mock_val = "name_value" assert arg == mock_val @pytest.mark.asyncio -async def test_create_asset_flattened_error_async(): +async def test_get_dvr_session_flattened_error_async(): client = LivestreamServiceAsyncClient( credentials=async_anonymous_credentials(), ) @@ -10900,22 +10890,20 @@ 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(), - parent="parent_value", - asset=resources.Asset(name="name_value"), - asset_id="asset_id_value", + await client.get_dvr_session( + service.GetDvrSessionRequest(), + name="name_value", ) @pytest.mark.parametrize( "request_type", [ - service.DeleteAssetRequest, + service.DeleteDvrSessionRequest, dict, ], ) -def test_delete_asset(request_type, transport: str = "grpc"): +def test_delete_dvr_session(request_type, transport: str = "grpc"): client = LivestreamServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -10926,22 +10914,24 @@ 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.delete_dvr_session), "__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) + 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.DeleteAssetRequest() + request = service.DeleteDvrSessionRequest() 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(): +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( @@ -10952,26 +10942,26 @@ 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( + request = service.DeleteDvrSessionRequest( 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: + 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.delete_asset(request=request) + client.delete_dvr_session(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == service.DeleteAssetRequest( + assert args[0] == service.DeleteDvrSessionRequest( name="name_value", - request_id="request_id_value", ) -def test_delete_asset_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: @@ -10985,16 +10975,20 @@ 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.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_asset] = mock_rpc + client._transport._wrapped_methods[ + client._transport.delete_dvr_session + ] = mock_rpc request = {} - client.delete_asset(request) + client.delete_dvr_session(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 @@ -11004,7 +10998,7 @@ def test_delete_asset_use_cached_wrapped_rpc(): # Subsequent calls should use the cached wrapper wrapper_fn.reset_mock() - client.delete_asset(request) + client.delete_dvr_session(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -11012,7 +11006,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_delete_dvr_session_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", ): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, @@ -11029,7 +11023,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.delete_dvr_session in client._client._transport._wrapped_methods ) @@ -11037,11 +11031,11 @@ 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.delete_dvr_session ] = mock_rpc request = {} - await client.delete_asset(request) + await client.delete_dvr_session(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 @@ -11051,7 +11045,7 @@ async def test_delete_asset_async_use_cached_wrapped_rpc( # Subsequent calls should use the cached wrapper wrapper_fn.reset_mock() - await client.delete_asset(request) + await client.delete_dvr_session(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -11059,8 +11053,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_delete_dvr_session_async( + transport: str = "grpc_asyncio", request_type=service.DeleteDvrSessionRequest ): client = LivestreamServiceAsyncClient( credentials=async_anonymous_credentials(), @@ -11072,17 +11066,19 @@ 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.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") ) - response = await client.delete_asset(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.DeleteAssetRequest() + request = service.DeleteDvrSessionRequest() assert args[0] == request # Establish that the response is the type that we expect. @@ -11090,25 +11086,27 @@ async def test_delete_asset_async( @pytest.mark.asyncio -async def test_delete_asset_async_from_dict(): - await test_delete_asset_async(request_type=dict) +async def test_delete_dvr_session_async_from_dict(): + await test_delete_dvr_session_async(request_type=dict) -def test_delete_asset_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.DeleteAssetRequest() + request = service.DeleteDvrSessionRequest() 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: + with mock.patch.object( + type(client.transport.delete_dvr_session), "__call__" + ) as call: call.return_value = operations_pb2.Operation(name="operations/op") - client.delete_asset(request) + client.delete_dvr_session(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 @@ -11124,23 +11122,25 @@ def test_delete_asset_field_headers(): @pytest.mark.asyncio -async def test_delete_asset_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.DeleteAssetRequest() + request = service.DeleteDvrSessionRequest() 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: + with mock.patch.object( + type(client.transport.delete_dvr_session), "__call__" + ) as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( operations_pb2.Operation(name="operations/op") ) - await client.delete_asset(request) + await client.delete_dvr_session(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) @@ -11155,18 +11155,20 @@ async def test_delete_asset_field_headers_async(): ) in kw["metadata"] -def test_delete_asset_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.delete_asset), "__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 = 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( + client.delete_dvr_session( name="name_value", ) @@ -11179,7 +11181,7 @@ def test_delete_asset_flattened(): assert arg == mock_val -def test_delete_asset_flattened_error(): +def test_delete_dvr_session_flattened_error(): client = LivestreamServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -11187,20 +11189,22 @@ 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(), + client.delete_dvr_session( + service.DeleteDvrSessionRequest(), name="name_value", ) @pytest.mark.asyncio -async def test_delete_asset_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.delete_asset), "__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 = operations_pb2.Operation(name="operations/op") @@ -11209,7 +11213,7 @@ async def test_delete_asset_flattened_async(): ) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - response = await client.delete_asset( + response = await client.delete_dvr_session( name="name_value", ) @@ -11223,7 +11227,7 @@ async def test_delete_asset_flattened_async(): @pytest.mark.asyncio -async def test_delete_asset_flattened_error_async(): +async def test_delete_dvr_session_flattened_error_async(): client = LivestreamServiceAsyncClient( credentials=async_anonymous_credentials(), ) @@ -11231,8 +11235,8 @@ 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(), + await client.delete_dvr_session( + service.DeleteDvrSessionRequest(), name="name_value", ) @@ -11240,11 +11244,11 @@ async def test_delete_asset_flattened_error_async(): @pytest.mark.parametrize( "request_type", [ - service.GetAssetRequest, + service.UpdateDvrSessionRequest, dict, ], ) -def test_get_asset(request_type, transport: str = "grpc"): +def test_update_dvr_session(request_type, transport: str = "grpc"): client = LivestreamServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -11255,29 +11259,24 @@ def test_get_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.get_asset), "__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.Asset( - name="name_value", - crc32c="crc32c_value", - state=resources.Asset.State.CREATING, - ) - response = client.get_asset(request) + call.return_value = operations_pb2.Operation(name="operations/spam") + response = 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.GetAssetRequest() + request = service.UpdateDvrSessionRequest() 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 + assert isinstance(response, future.Future) -def test_get_asset_non_empty_request_with_auto_populated_field(): +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( @@ -11288,24 +11287,22 @@ 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( - name="name_value", - ) + request = service.UpdateDvrSessionRequest() # 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.update_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.update_dvr_session(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == service.GetAssetRequest( - name="name_value", - ) + assert args[0] == service.UpdateDvrSessionRequest() -def test_get_asset_use_cached_wrapped_rpc(): +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: @@ -11319,21 +11316,30 @@ 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.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.get_asset] = mock_rpc + client._transport._wrapped_methods[ + client._transport.update_dvr_session + ] = mock_rpc request = {} - client.get_asset(request) + client.update_dvr_session(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.get_asset(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_dvr_session(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -11341,7 +11347,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_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: @@ -11356,7 +11364,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.update_dvr_session in client._client._transport._wrapped_methods ) @@ -11364,16 +11372,21 @@ 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.update_dvr_session ] = mock_rpc request = {} - await client.get_asset(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_asset(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 @@ -11381,8 +11394,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_update_dvr_session_async( + transport: str = "grpc_asyncio", request_type=service.UpdateDvrSessionRequest ): client = LivestreamServiceAsyncClient( credentials=async_anonymous_credentials(), @@ -11394,50 +11407,47 @@ 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.update_dvr_session), "__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, - ) + operations_pb2.Operation(name="operations/spam") ) - response = await client.get_asset(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.GetAssetRequest() + request = service.UpdateDvrSessionRequest() 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 + assert isinstance(response, future.Future) @pytest.mark.asyncio -async def test_get_asset_async_from_dict(): - await test_get_asset_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_asset_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.GetAssetRequest() + 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_asset), "__call__") as call: - call.return_value = resources.Asset() - client.get_asset(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 @@ -11448,26 +11458,30 @@ def test_get_asset_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_asset_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.GetAssetRequest() + 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_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.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) @@ -11478,35 +11492,41 @@ async def test_get_asset_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_asset_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_asset), "__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.Asset() + 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_asset( - 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_asset_flattened_error(): +def test_update_dvr_session_flattened_error(): client = LivestreamServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -11514,41 +11534,50 @@ 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(), - 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_asset_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_asset), "__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.Asset() + call.return_value = operations_pb2.Operation(name="operations/op") - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.Asset()) + 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_asset( - 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_asset_flattened_error_async(): +async def test_update_dvr_session_flattened_error_async(): client = LivestreamServiceAsyncClient( credentials=async_anonymous_credentials(), ) @@ -11556,20 +11585,21 @@ 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(), - 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.ListAssetsRequest, + service.CreateAssetRequest, dict, ], ) -def test_list_assets(request_type, transport: str = "grpc"): +def test_create_asset(request_type, transport: str = "grpc"): client = LivestreamServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -11580,27 +11610,22 @@ 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.create_asset), "__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.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.ListAssetsRequest() + request = service.CreateAssetRequest() 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_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( @@ -11611,30 +11636,28 @@ 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( + request = service.CreateAssetRequest( parent="parent_value", - page_token="page_token_value", - filter="filter_value", - order_by="order_by_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.list_assets), "__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.list_assets(request=request) + client.create_asset(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == service.ListAssetsRequest( + assert args[0] == service.CreateAssetRequest( parent="parent_value", - page_token="page_token_value", - filter="filter_value", - order_by="order_by_value", + asset_id="asset_id_value", + request_id="request_id_value", ) -def test_list_assets_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: @@ -11648,21 +11671,26 @@ 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.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.list_assets] = mock_rpc + client._transport._wrapped_methods[client._transport.create_asset] = mock_rpc request = {} - client.list_assets(request) + client.create_asset(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.create_asset(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -11670,7 +11698,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_create_asset_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", ): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, @@ -11687,7 +11715,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.create_asset in client._client._transport._wrapped_methods ) @@ -11695,16 +11723,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.create_asset ] = mock_rpc request = {} - await client.list_assets(request) + await client.create_asset(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.create_asset(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -11712,8 +11745,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_create_asset_async( + transport: str = "grpc_asyncio", request_type=service.CreateAssetRequest ): client = LivestreamServiceAsyncClient( credentials=async_anonymous_credentials(), @@ -11725,48 +11758,43 @@ 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.create_asset), "__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.create_asset(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.CreateAssetRequest() 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_create_asset_async_from_dict(): + await test_create_asset_async(request_type=dict) -def test_list_assets_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.ListAssetsRequest() + request = service.CreateAssetRequest() 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 = service.ListAssetsResponse() - client.list_assets(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) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 @@ -11782,23 +11810,23 @@ def test_list_assets_field_headers(): @pytest.mark.asyncio -async def test_list_assets_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.ListAssetsRequest() + request = service.CreateAssetRequest() 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: + with mock.patch.object(type(client.transport.create_asset), "__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.create_asset(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) @@ -11813,19 +11841,21 @@ async def test_list_assets_field_headers_async(): ) in kw["metadata"] -def test_list_assets_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.list_assets), "__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 = 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( + 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 @@ -11835,9 +11865,15 @@ def test_list_assets_flattened(): arg = args[0].parent mock_val = "parent_value" assert arg == mock_val + 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_list_assets_flattened_error(): +def test_create_asset_flattened_error(): client = LivestreamServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -11845,30 +11881,34 @@ 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(), + 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_list_assets_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.list_assets), "__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 = 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( + 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 @@ -11878,10 +11918,16 @@ async def test_list_assets_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") + assert arg == mock_val + arg = args[0].asset_id + mock_val = "asset_id_value" + assert arg == mock_val @pytest.mark.asyncio -async def test_list_assets_flattened_error_async(): +async def test_create_asset_flattened_error_async(): client = LivestreamServiceAsyncClient( credentials=async_anonymous_credentials(), ) @@ -11889,271 +11935,78 @@ 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(), + await client.create_asset( + service.CreateAssetRequest(), parent="parent_value", + asset=resources.Asset(name="name_value"), + asset_id="asset_id_value", ) -def test_list_assets_pager(transport_name: str = "grpc"): +@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_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.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) - 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.DeleteAssetRequest() + 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_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=transport_name, + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = 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.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, + 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", ) - 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(), - ) - # 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, - ) - 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) - - assert len(responses) == 6 - assert all(isinstance(i, resources.Asset) for i in responses) - - -@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) - - # 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(): +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: @@ -12167,21 +12020,26 @@ def test_get_pool_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_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_pool] = mock_rpc + client._transport._wrapped_methods[client._transport.delete_asset] = mock_rpc request = {} - client.get_pool(request) + client.delete_asset(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - 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() + + client.delete_asset(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -12189,7 +12047,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_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: @@ -12204,7 +12064,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.delete_asset in client._client._transport._wrapped_methods ) @@ -12212,16 +12072,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.delete_asset ] = mock_rpc request = {} - await client.get_pool(request) + await client.delete_asset(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.delete_asset(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -12229,8 +12094,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_delete_asset_async( + transport: str = "grpc_asyncio", request_type=service.DeleteAssetRequest ): client = LivestreamServiceAsyncClient( credentials=async_anonymous_credentials(), @@ -12242,46 +12107,43 @@ 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.delete_asset), "__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.delete_asset(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.DeleteAssetRequest() 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_delete_asset_async_from_dict(): + await test_delete_asset_async(request_type=dict) -def test_get_pool_field_headers(): +def test_delete_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.GetPoolRequest() + 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.get_pool), "__call__") as call: - call.return_value = resources.Pool() - client.get_pool(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) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 @@ -12297,21 +12159,23 @@ def test_get_pool_field_headers(): @pytest.mark.asyncio -async def test_get_pool_field_headers_async(): +async def test_delete_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.GetPoolRequest() + 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.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.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) @@ -12326,18 +12190,18 @@ async def test_get_pool_field_headers_async(): ) in kw["metadata"] -def test_get_pool_flattened(): +def test_delete_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.get_pool), "__call__") as call: + with mock.patch.object(type(client.transport.delete_asset), "__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( + client.delete_asset( name="name_value", ) @@ -12350,7 +12214,7 @@ def test_get_pool_flattened(): assert arg == mock_val -def test_get_pool_flattened_error(): +def test_delete_asset_flattened_error(): client = LivestreamServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -12358,27 +12222,29 @@ 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(), + client.delete_asset( + service.DeleteAssetRequest(), name="name_value", ) @pytest.mark.asyncio -async def test_get_pool_flattened_async(): +async def test_delete_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_pool), "__call__") as call: + with mock.patch.object(type(client.transport.delete_asset), "__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( + response = await client.delete_asset( name="name_value", ) @@ -12392,7 +12258,7 @@ async def test_get_pool_flattened_async(): @pytest.mark.asyncio -async def test_get_pool_flattened_error_async(): +async def test_delete_asset_flattened_error_async(): client = LivestreamServiceAsyncClient( credentials=async_anonymous_credentials(), ) @@ -12400,8 +12266,8 @@ 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(), + await client.delete_asset( + service.DeleteAssetRequest(), name="name_value", ) @@ -12409,11 +12275,11 @@ async def test_get_pool_flattened_error_async(): @pytest.mark.parametrize( "request_type", [ - service.UpdatePoolRequest, + service.GetAssetRequest, dict, ], ) -def test_update_pool(request_type, transport: str = "grpc"): +def test_get_asset(request_type, transport: str = "grpc"): client = LivestreamServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -12424,22 +12290,29 @@ 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.get_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) + call.return_value = resources.Asset( + name="name_value", + crc32c="crc32c_value", + state=resources.Asset.State.CREATING, + ) + 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.UpdatePoolRequest() + request = service.GetAssetRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) + assert isinstance(response, resources.Asset) + assert response.name == "name_value" + assert response.crc32c == "crc32c_value" + assert response.state == resources.Asset.State.CREATING -def test_update_pool_non_empty_request_with_auto_populated_field(): +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( @@ -12450,24 +12323,24 @@ 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_id="request_id_value", + request = service.GetAssetRequest( + name="name_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.get_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.get_asset(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == service.UpdatePoolRequest( - request_id="request_id_value", + assert args[0] == service.GetAssetRequest( + name="name_value", ) -def test_update_pool_use_cached_wrapped_rpc(): +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: @@ -12481,26 +12354,21 @@ 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.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.update_pool] = mock_rpc + client._transport._wrapped_methods[client._transport.get_asset] = mock_rpc request = {} - client.update_pool(request) + client.get_asset(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - # Operation methods call wrapper_fn to build a cached - # client._transport.operations_client instance on first rpc call. - # Subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() - - client.update_pool(request) + client.get_asset(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -12508,9 +12376,7 @@ def test_update_pool_use_cached_wrapped_rpc(): @pytest.mark.asyncio -async def test_update_pool_async_use_cached_wrapped_rpc( - transport: str = "grpc_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: @@ -12525,7 +12391,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.get_asset in client._client._transport._wrapped_methods ) @@ -12533,21 +12399,16 @@ 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.get_asset ] = mock_rpc request = {} - await client.update_pool(request) + await client.get_asset(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - # Operation methods call wrapper_fn to build a cached - # client._transport.operations_client instance on first rpc call. - # Subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() - - await client.update_pool(request) + await client.get_asset(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -12555,8 +12416,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_get_asset_async( + transport: str = "grpc_asyncio", request_type=service.GetAssetRequest ): client = LivestreamServiceAsyncClient( credentials=async_anonymous_credentials(), @@ -12568,43 +12429,50 @@ 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.get_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") + resources.Asset( + name="name_value", + crc32c="crc32c_value", + state=resources.Asset.State.CREATING, + ) ) - response = await client.update_pool(request) + response = await client.get_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.GetAssetRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) + assert isinstance(response, resources.Asset) + assert response.name == "name_value" + assert response.crc32c == "crc32c_value" + assert response.state == resources.Asset.State.CREATING @pytest.mark.asyncio -async def test_update_pool_async_from_dict(): - await test_update_pool_async(request_type=dict) +async def test_get_asset_async_from_dict(): + await test_get_asset_async(request_type=dict) -def test_update_pool_field_headers(): +def test_get_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.GetAssetRequest() - request.pool.name = "name_value" + request.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.update_pool), "__call__") as call: - call.return_value = operations_pb2.Operation(name="operations/op") - client.update_pool(request) + with mock.patch.object(type(client.transport.get_asset), "__call__") as call: + call.return_value = resources.Asset() + client.get_asset(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 @@ -12615,28 +12483,26 @@ def test_update_pool_field_headers(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "pool.name=name_value", + "name=name_value", ) in kw["metadata"] @pytest.mark.asyncio -async def test_update_pool_field_headers_async(): +async def test_get_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.GetAssetRequest() - request.pool.name = "name_value" + request.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.update_pool), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/op") - ) - await client.update_pool(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) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) @@ -12647,39 +12513,35 @@ async def test_update_pool_field_headers_async(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "pool.name=name_value", + "name=name_value", ) in kw["metadata"] -def test_update_pool_flattened(): +def test_get_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.get_asset), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name="operations/op") + call.return_value = resources.Asset() # 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.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].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"]) + arg = args[0].name + mock_val = "name_value" assert arg == mock_val -def test_update_pool_flattened_error(): +def test_get_asset_flattened_error(): client = LivestreamServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -12687,48 +12549,41 @@ 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.get_asset( + service.GetAssetRequest(), + name="name_value", ) @pytest.mark.asyncio -async def test_update_pool_flattened_async(): +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.update_pool), "__call__") as call: + with mock.patch.object(type(client.transport.get_asset), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name="operations/op") + call.return_value = resources.Asset() - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") - ) + 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.update_pool( - pool=resources.Pool(name="name_value"), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + response = await client.get_asset( + 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].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"]) + arg = args[0].name + mock_val = "name_value" assert arg == mock_val @pytest.mark.asyncio -async def test_update_pool_flattened_error_async(): +async def test_get_asset_flattened_error_async(): client = LivestreamServiceAsyncClient( credentials=async_anonymous_credentials(), ) @@ -12736,233 +12591,91 @@ 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.get_asset( + service.GetAssetRequest(), + name="name_value", ) -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: - 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.parametrize( + "request_type", + [ + service.ListAssetsRequest, + dict, + ], +) +def test_list_assets(request_type, transport: str = "grpc"): + client = LivestreamServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) - # Ensure method has been cached - assert client._transport.create_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.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"], ) - client._transport._wrapped_methods[client._transport.create_channel_] = mock_rpc - - request = {} - client.create_channel(request) + response = 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 - wrapper_fn.reset_mock() + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = service.ListAssetsRequest() + assert args[0] == request - client.create_channel(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"] - # Establish 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_non_empty_request_with_auto_populated_field(): + # 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", + ) -def test_create_channel_rest_required_fields(request_type=service.CreateChannelRequest): - transport_class = transports.LivestreamServiceRestTransport - - 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) - ) - - # verify fields with default values are dropped - assert "channelId" not in jsonified_request - - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).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["parent"] = "parent_value" - jsonified_request["channelId"] = "channel_id_value" - - 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", - ) - ) - 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" - - 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_channel(request) - - expected_params = [ - ( - "channelId", - "", - ), - ("$alt", "json;enum-encoding=int"), - ] - actual_params = req.call_args.kwargs["params"] - assert expected_params == actual_params - - -def test_create_channel_rest_unset_required_fields(): - transport = transports.LivestreamServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials - ) - - unset_fields = transport.create_channel_._get_unset_required_fields({}) - assert set(unset_fields) == ( - set( - ( - "channelId", - "requestId", - ) - ) - & set( - ( - "parent", - "channel", - "channelId", - ) - ) - ) - - -def test_create_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.ListAssetsRequest( + parent="parent_value", + page_token="page_token_value", + filter="filter_value", + order_by="order_by_value", ) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), "request") as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name="operations/spam") - - # get arguments that satisfy an http rule for this method - sample_request = {"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_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], + # 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. ) - - -def test_create_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.create_channel( - service.CreateChannelRequest(), + client.list_assets(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == service.ListAssetsRequest( parent="parent_value", - channel=resources.Channel(name="name_value"), - channel_id="channel_id_value", + page_token="page_token_value", + filter="filter_value", + order_by="order_by_value", ) -def test_list_channels_rest_use_cached_wrapped_rpc(): +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 @@ -12970,254 +12683,518 @@ def test_list_channels_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.list_channels 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.list_channels] = mock_rpc - + client._transport._wrapped_methods[client._transport.list_assets] = mock_rpc request = {} - client.list_channels(request) + client.list_assets(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.list_channels(request) + 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_channels_rest_required_fields(request_type=service.ListChannelsRequest): - transport_class = transports.LivestreamServiceRestTransport +@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, + ) - request_init = {} - request_init["parent"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads( - json_format.MessageToJson(pb_request, use_integers_for_enums=False) - ) + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() - # verify fields with default values are dropped + # Ensure method has been cached + assert ( + client._client._transport.list_assets + in client._client._transport._wrapped_methods + ) - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).list_channels._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.list_assets + ] = mock_rpc - # verify required fields with default values are now present + request = {} + await client.list_assets(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_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) + await client.list_assets(request) - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == "parent_value" + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@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, + ) + + # Everything is optional in proto3 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 = grpc_helpers_async.FakeUnaryUnaryCall( + service.ListAssetsResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], + ) + ) + response = await client.list_assets(request) + # 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 + + # 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"] + + +@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 = 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 + # Any value 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() - # Convert return value to protobuf type - return_value = service.ListChannelsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) + request.parent = "parent_value" - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_assets), "__call__") as call: + call.return_value = service.ListAssetsResponse() + client.list_assets(request) - response = client.list_channels(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_list_channels_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.list_channels._get_unset_required_fields({}) - assert set(unset_fields) == ( - set( - ( - "filter", - "orderBy", - "pageSize", - "pageToken", - ) + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = 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(("parent",)) - ) + 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_list_channels_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 = service.ListChannelsResponse() + # 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", + ) - # get arguments that satisfy an http rule for this method - sample_request = {"parent": "projects/sample1/locations/sample2"} + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val - # get truthy value for each flattened field - mock_args = dict( + +def test_list_assets_flattened_error(): + client = LivestreamServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_assets( + service.ListAssetsRequest(), 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.list_channels(**mock_args) +@pytest.mark.asyncio +async def test_list_assets_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: + # Designate an appropriate return value for the call. + call.return_value = service.ListAssetsResponse() + + 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", + ) # Establish that the underlying call was 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) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val -def test_list_channels_rest_flattened_error(transport: str = "rest"): - client = LivestreamServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, +@pytest.mark.asyncio +async def test_list_assets_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.list_channels( - service.ListChannelsRequest(), + await client.list_assets( + service.ListAssetsRequest(), parent="parent_value", ) -def test_list_channels_rest_pager(transport: str = "rest"): +def test_list_assets_pager(transport_name: str = "grpc"): client = LivestreamServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport=transport, + transport=transport_name, ) - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, "request") as req: - # TODO(kbandes): remove this mock unless there's a good reason for it. - # with mock.patch.object(path_template, 'transcode') as transcode: - # Set the response as a series of pages - response = ( - service.ListChannelsResponse( - channels=[ - resources.Channel(), - resources.Channel(), - resources.Channel(), + # 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.ListChannelsResponse( - channels=[], + service.ListAssetsResponse( + assets=[], next_page_token="def", ), - service.ListChannelsResponse( - channels=[ - resources.Channel(), + service.ListAssetsResponse( + assets=[ + resources.Asset(), ], next_page_token="ghi", ), - service.ListChannelsResponse( - channels=[ - resources.Channel(), - resources.Channel(), + service.ListAssetsResponse( + assets=[ + resources.Asset(), + resources.Asset(), ], ), + RuntimeError, ) - # 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"} + 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) - pager = client.list_channels(request=sample_request) + assert pager._metadata == expected_metadata + assert pager._retry == retry + assert pager._timeout == timeout results = list(pager) assert len(results) == 6 - assert all(isinstance(i, resources.Channel) for i in results) + assert all(isinstance(i, resources.Asset) for i in results) - pages = list(client.list_channels(request=sample_request).pages) + +def test_list_assets_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_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 -def test_get_channel_rest_use_cached_wrapped_rpc(): +@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, + ) + 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) + + assert len(responses) == 6 + assert all(isinstance(i, resources.Asset) for i in responses) + + +@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) + + # 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="rest", + transport="grpc", ) # Should wrap all calls on client creation @@ -13225,363 +13202,313 @@ def test_get_channel_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.get_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.get_channel] = mock_rpc - + client._transport._wrapped_methods[client._transport.get_pool] = mock_rpc request = {} - client.get_channel(request) + client.get_pool(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.get_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_get_channel_rest_required_fields(request_type=service.GetChannelRequest): - 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() + + # Ensure method has been cached + assert ( + client._client._transport.get_pool + 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_pool + ] = mock_rpc + + request = {} + await client.get_pool(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await 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 + + +@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, ) - # 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() - ).get_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.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) - # 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.GetPoolRequest() + assert args[0] == request - jsonified_request["name"] = "name_value" + # Establish that the response is the type that we expect. + assert isinstance(response, resources.Pool) + assert response.name == "name_value" - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).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" +@pytest.mark.asyncio +async def test_get_pool_async_from_dict(): + await test_get_pool_async(request_type=dict) + +def test_get_pool_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 = 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.GetPoolRequest() - # 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_pool), "__call__") as call: + call.return_value = resources.Pool() + client.get_pool(request) - response = client.get_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", + "name=name_value", + ) in kw["metadata"] -def test_get_channel_rest_unset_required_fields(): - transport = transports.LivestreamServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials +@pytest.mark.asyncio +async def test_get_pool_field_headers_async(): + client = LivestreamServiceAsyncClient( + credentials=async_anonymous_credentials(), ) - unset_fields = transport.get_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_get_channel_rest_flattened(): + # 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) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] + + +def test_get_pool_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.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( + # 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", ) - mock_args.update(sample_request) - - # 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) # Establish that the underlying call was 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].name + mock_val = "name_value" + assert arg == mock_val -def test_get_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.get_channel( - service.GetChannelRequest(), + client.get_pool( + service.GetPoolRequest(), name="name_value", ) -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: - client = LivestreamServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) +@pytest.mark.asyncio +async def test_get_pool_flattened_async(): + client = LivestreamServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_pool), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = resources.Pool() - # Ensure method has been cached - 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.delete_channel] = mock_rpc - - request = {} - client.delete_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.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 + 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", + ) + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val -def test_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_get_pool_flattened_error_async(): + client = LivestreamServiceAsyncClient( + credentials=async_anonymous_credentials(), ) - # verify fields with default values are dropped - - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).delete_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() - ).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", + # 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", ) - ) - 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.parametrize( + "request_type", + [ + service.UpdatePoolRequest, + dict, + ], +) +def test_update_pool(request_type, transport: str = "grpc"): client = LivestreamServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport=transport, ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name="operations/spam") - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, "request") as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, "transcode") as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - "uri": "v1/sample_method", - "method": "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_channel(request) - - expected_params = [("$alt", "json;enum-encoding=int")] - actual_params = req.call_args.kwargs["params"] - assert expected_params == actual_params + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.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) -def test_delete_channel_rest_unset_required_fields(): - transport = transports.LivestreamServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials - ) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = service.UpdatePoolRequest() + assert args[0] == request - unset_fields = transport.delete_channel._get_unset_required_fields({}) - assert set(unset_fields) == ( - set( - ( - "force", - "requestId", - ) - ) - & set(("name",)) - ) + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) -def test_delete_channel_rest_flattened(): +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", + transport="grpc", ) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), "request") as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name="operations/spam") - - # get arguments that satisfy an http rule for this method - sample_request = {"name": "projects/sample1/locations/sample2/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.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], - ) - - -def test_delete_channel_rest_flattened_error(transport: str = "rest"): - client = LivestreamServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = service.UpdatePoolRequest( + request_id="request_id_value", ) - # 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", + # 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. + ) + 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_update_channel_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 @@ -13589,227 +13516,314 @@ def test_update_channel_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.update_channel 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.update_channel] = mock_rpc - + client._transport._wrapped_methods[client._transport.update_pool] = mock_rpc request = {} - client.update_channel(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 + # 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_channel(request) + 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_channel_rest_required_fields(request_type=service.UpdateChannelRequest): - 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 = 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() - ).update_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.update_pool + ] = mock_rpc - # verify required fields with default values are now present + request = {} + await client.update_pool(request) - 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", - ) + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.update_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 + + +@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, ) - jsonified_request.update(unset_fields) - # verify required fields with non-default values are left alone + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.update_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) + + # 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 + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + +@pytest.mark.asyncio +async def test_update_pool_async_from_dict(): + await test_update_pool_async(request_type=dict) + + +def test_update_pool_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": "patch", - "query_params": pb_request, - } - transcode_result["body"] = pb_request - transcode.return_value = transcode_result + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.UpdatePoolRequest() - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) + request.pool.name = "name_value" - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.update_pool), "__call__") as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.update_pool(request) - response = client.update_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", + "pool.name=name_value", + ) in kw["metadata"] -def test_update_channel_rest_unset_required_fields(): - transport = transports.LivestreamServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials +@pytest.mark.asyncio +async def test_update_pool_field_headers_async(): + client = LivestreamServiceAsyncClient( + credentials=async_anonymous_credentials(), ) - unset_fields = transport.update_channel._get_unset_required_fields({}) - assert set(unset_fields) == ( - set( - ( - "requestId", - "updateMask", - ) + # Any value 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" + + # 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") ) - & set(("channel",)) - ) + await client.update_pool(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_update_channel_rest_flattened(): + # 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(), - transport="rest", ) - # Mock the http request call within the method and fake a response. - with mock.patch.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 = { - "channel": {"name": "projects/sample1/locations/sample2/channels/sample3"} - } - - # get truthy value for each flattened field - mock_args = dict( - channel=resources.Channel(name="name_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: + # 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"]), ) - 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_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], - ) + 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_update_channel_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.update_channel( - service.UpdateChannelRequest(), - channel=resources.Channel(name="name_value"), + client.update_pool( + service.UpdatePoolRequest(), + pool=resources.Pool(name="name_value"), update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) -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", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() +@pytest.mark.asyncio +async def test_update_pool_flattened_async(): + client = LivestreamServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) - # Ensure method has been cached - assert client._transport.start_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.update_pool), "__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.update_pool( + pool=resources.Pool(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) - client._transport._wrapped_methods[client._transport.start_channel] = mock_rpc - - request = {} - client.start_channel(request) - # Establish that the underlying gRPC stub method was called. + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, 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 + + +@pytest.mark.asyncio +async def test_update_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.update_pool( + service.UpdatePoolRequest(), + pool=resources.Pool(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +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: + 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_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_channel_] = mock_rpc + + request = {} + client.create_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.start_channel(request) + 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_start_channel_rest_required_fields(request_type=service.StartChannelRequest): +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( @@ -13817,24 +13831,37 @@ def test_start_channel_rest_required_fields(request_type=service.StartChannelReq ) # verify fields with default values are dropped + assert "channelId" not in jsonified_request unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).start_channel._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() - ).start_channel._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(), @@ -13869,23 +13896,43 @@ def test_start_channel_rest_required_fields(request_type=service.StartChannelReq req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.start_channel(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_start_channel_rest_unset_required_fields(): +def test_create_channel_rest_unset_required_fields(): transport = transports.LivestreamServiceRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.start_channel._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_start_channel_rest_flattened(): +def test_create_channel_rest_flattened(): client = LivestreamServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -13897,11 +13944,13 @@ def test_start_channel_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"} + 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) @@ -13913,20 +13962,19 @@ def test_start_channel_rest_flattened(): req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.start_channel(**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/*/channels/*}:start" - % client.transport._host, + "%s/v1/{parent=projects/*/locations/*}/channels" % client.transport._host, args[1], ) -def test_start_channel_rest_flattened_error(transport: str = "rest"): +def test_create_channel_rest_flattened_error(transport: str = "rest"): client = LivestreamServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -13935,13 +13983,15 @@ def test_start_channel_rest_flattened_error(transport: str = "rest"): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.start_channel( - service.StartChannelRequest(), - name="name_value", + client.create_channel( + service.CreateChannelRequest(), + parent="parent_value", + channel=resources.Channel(name="name_value"), + channel_id="channel_id_value", ) -def test_stop_channel_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: @@ -13955,37 +14005,33 @@ 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.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.stop_channel] = mock_rpc + client._transport._wrapped_methods[client._transport.list_channels] = mock_rpc request = {} - client.stop_channel(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.stop_channel(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_stop_channel_rest_required_fields(request_type=service.StopChannelRequest): +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( @@ -13996,21 +14042,30 @@ def test_stop_channel_rest_required_fields(request_type=service.StopChannelReque unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).stop_channel._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() - ).stop_channel._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( + ( + "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(), @@ -14019,7 +14074,7 @@ def test_stop_channel_rest_required_fields(request_type=service.StopChannelReque 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 @@ -14031,37 +14086,49 @@ def test_stop_channel_rest_required_fields(request_type=service.StopChannelReque 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 = 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.stop_channel(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_stop_channel_rest_unset_required_fields(): +def test_list_channels_rest_unset_required_fields(): transport = transports.LivestreamServiceRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.stop_channel._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name",))) + unset_fields = transport.list_channels._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "filter", + "orderBy", + "pageSize", + "pageToken", + ) + ) + & set(("parent",)) + ) -def test_stop_channel_rest_flattened(): +def test_list_channels_rest_flattened(): client = LivestreamServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -14070,39 +14137,40 @@ def test_stop_channel_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/channels/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.stop_channel(**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/*/channels/*}:stop" - % client.transport._host, + "%s/v1/{parent=projects/*/locations/*}/channels" % client.transport._host, args[1], ) -def test_stop_channel_rest_flattened_error(transport: str = "rest"): +def test_list_channels_rest_flattened_error(transport: str = "rest"): client = LivestreamServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -14111,58 +14179,114 @@ def test_stop_channel_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.stop_channel( - service.StopChannelRequest(), - 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", + client.list_channels( + service.ListChannelsRequest(), + 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_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_input] = mock_rpc - request = {} - client.create_input(request) +def test_list_channels_rest_pager(transport: str = "rest"): + client = LivestreamServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 + # 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 - # Operation methods build a cached wrapper on first rpc call - # subsequent calls should use the cached wrapper + # 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() - client.create_input(request) + # 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_create_input_rest_required_fields(request_type=service.CreateInputRequest): +def test_get_channel_rest_required_fields(request_type=service.GetChannelRequest): transport_class = transports.LivestreamServiceRestTransport request_init = {} - request_init["parent"] = "" - request_init["input_id"] = "" + request_init["name"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -14170,37 +14294,24 @@ def test_create_input_rest_required_fields(request_type=service.CreateInputReque ) # 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) + ).get_channel._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" + jsonified_request["name"] = "name_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", - ) - ) + ).get_channel._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 "inputId" in jsonified_request - assert jsonified_request["inputId"] == "input_id_value" + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" client = LivestreamServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -14209,7 +14320,7 @@ def test_create_input_rest_required_fields(request_type=service.CreateInputReque 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 @@ -14221,57 +14332,39 @@ def test_create_input_rest_required_fields(request_type=service.CreateInputReque 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.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.create_input(request) + response = client.get_channel(request) - expected_params = [ - ( - "inputId", - "", - ), - ("$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_input_rest_unset_required_fields(): +def test_get_channel_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", - ) - ) - ) + unset_fields = transport.get_channel._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) -def test_create_input_rest_flattened(): +def test_get_channel_rest_flattened(): client = LivestreamServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -14280,40 +14373,40 @@ def test_create_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 = {"parent": "projects/sample1/locations/sample2"} + sample_request = {"name": "projects/sample1/locations/sample2/channels/sample3"} # get truthy value for each flattened field mock_args = dict( - parent="parent_value", - input=resources.Input(name="name_value"), - input_id="input_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.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.create_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/{parent=projects/*/locations/*}/inputs" % client.transport._host, + "%s/v1/{name=projects/*/locations/*/channels/*}" % client.transport._host, args[1], ) -def test_create_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, @@ -14322,15 +14415,13 @@ def test_create_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.create_input( - service.CreateInputRequest(), - parent="parent_value", - input=resources.Input(name="name_value"), - input_id="input_id_value", + client.get_channel( + service.GetChannelRequest(), + name="name_value", ) -def test_list_inputs_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: @@ -14344,33 +14435,37 @@ 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.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.list_inputs] = mock_rpc + client._transport._wrapped_methods[client._transport.delete_channel] = mock_rpc request = {} - client.list_inputs(request) + client.delete_channel(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.list_inputs(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_list_inputs_rest_required_fields(request_type=service.ListInputsRequest): +def test_delete_channel_rest_required_fields(request_type=service.DeleteChannelRequest): 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( @@ -14381,30 +14476,28 @@ def test_list_inputs_rest_required_fields(request_type=service.ListInputsRequest unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).list_inputs._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 - jsonified_request["parent"] = "parent_value" + jsonified_request["name"] = "name_value" unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).list_inputs._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( ( - "filter", - "order_by", - "page_size", - "page_token", + "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 "name" in jsonified_request + assert jsonified_request["name"] == "name_value" client = LivestreamServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -14413,7 +14506,7 @@ def test_list_inputs_rest_required_fields(request_type=service.ListInputsRequest request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = service.ListInputsResponse() + 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 @@ -14425,49 +14518,44 @@ def test_list_inputs_rest_required_fields(request_type=service.ListInputsRequest 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 = 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.list_inputs(request) + response = client.delete_channel(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_list_inputs_rest_unset_required_fields(): +def test_delete_channel_rest_unset_required_fields(): transport = transports.LivestreamServiceRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.list_inputs._get_unset_required_fields({}) + unset_fields = transport.delete_channel._get_unset_required_fields({}) assert set(unset_fields) == ( set( ( - "filter", - "orderBy", - "pageSize", - "pageToken", + "force", + "requestId", ) ) - & set(("parent",)) + & set(("name",)) ) -def test_list_inputs_rest_flattened(): +def test_delete_channel_rest_flattened(): client = LivestreamServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -14476,40 +14564,38 @@ def test_list_inputs_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.ListInputsResponse() + return_value = operations_pb2.Operation(name="operations/spam") # get arguments that satisfy an http rule for this method - sample_request = {"parent": "projects/sample1/locations/sample2"} + sample_request = {"name": "projects/sample1/locations/sample2/channels/sample3"} # get truthy value for each flattened field mock_args = dict( - parent="parent_value", + name="name_value", ) mock_args.update(sample_request) # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 - # Convert return value to protobuf type - return_value = 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.list_inputs(**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/*}/inputs" % client.transport._host, + "%s/v1/{name=projects/*/locations/*/channels/*}" % client.transport._host, args[1], ) -def test_list_inputs_rest_flattened_error(transport: str = "rest"): +def test_delete_channel_rest_flattened_error(transport: str = "rest"): client = LivestreamServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -14518,74 +14604,13 @@ def test_list_inputs_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_inputs( - service.ListInputsRequest(), - parent="parent_value", + client.delete_channel( + service.DeleteChannelRequest(), + name="name_value", ) -def test_list_inputs_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.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 - - # 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 - - 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(): +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: @@ -14599,33 +14624,36 @@ 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.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.get_input] = mock_rpc + client._transport._wrapped_methods[client._transport.update_channel] = mock_rpc request = {} - client.get_input(request) + client.update_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.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_get_input_rest_required_fields(request_type=service.GetInputRequest): +def test_update_channel_rest_required_fields(request_type=service.UpdateChannelRequest): transport_class = transports.LivestreamServiceRestTransport request_init = {} - request_init["name"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -14636,21 +14664,24 @@ def test_get_input_rest_required_fields(request_type=service.GetInputRequest): unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).get_input._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["name"] = "name_value" - unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).get_input._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( + ( + "request_id", + "update_mask", + ) + ) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == "name_value" client = LivestreamServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -14659,7 +14690,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 @@ -14671,39 +14702,45 @@ 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": "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 = 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.update_channel(request) expected_params = [("$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_update_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.update_channel._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "requestId", + "updateMask", + ) + ) + & set(("channel",)) + ) -def test_get_input_rest_flattened(): +def test_update_channel_rest_flattened(): client = LivestreamServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -14712,40 +14749,42 @@ 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 = { + "channel": {"name": "projects/sample1/locations/sample2/channels/sample3"} + } # get truthy value for each flattened field mock_args = dict( - name="name_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 = 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.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/{name=projects/*/locations/*/inputs/*}" % client.transport._host, + "%s/v1/{channel.name=projects/*/locations/*/channels/*}" + % client.transport._host, args[1], ) -def test_get_input_rest_flattened_error(transport: str = "rest"): +def test_update_channel_rest_flattened_error(transport: str = "rest"): client = LivestreamServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -14754,13 +14793,14 @@ 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.update_channel( + service.UpdateChannelRequest(), + channel=resources.Channel(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) -def test_delete_input_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: @@ -14774,17 +14814,17 @@ 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.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.delete_input] = mock_rpc + client._transport._wrapped_methods[client._transport.start_channel] = mock_rpc request = {} - client.delete_input(request) + client.start_channel(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 @@ -14793,14 +14833,14 @@ def test_delete_input_rest_use_cached_wrapped_rpc(): # subsequent calls should use the cached wrapper wrapper_fn.reset_mock() - client.delete_input(request) + 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_delete_input_rest_required_fields(request_type=service.DeleteInputRequest): +def test_start_channel_rest_required_fields(request_type=service.StartChannelRequest): transport_class = transports.LivestreamServiceRestTransport request_init = {} @@ -14815,7 +14855,7 @@ 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) + ).start_channel._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present @@ -14824,9 +14864,7 @@ 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) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("request_id",)) + ).start_channel._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone @@ -14852,9 +14890,10 @@ 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": "post", "query_params": pb_request, } + transcode_result["body"] = pb_request transcode.return_value = transcode_result response_value = Response() @@ -14865,23 +14904,23 @@ def test_delete_input_rest_required_fields(request_type=service.DeleteInputReque req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.delete_input(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_delete_input_rest_unset_required_fields(): +def test_start_channel_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.start_channel._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) -def test_delete_input_rest_flattened(): +def test_start_channel_rest_flattened(): client = LivestreamServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -14893,7 +14932,7 @@ def test_delete_input_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/inputs/sample3"} + sample_request = {"name": "projects/sample1/locations/sample2/channels/sample3"} # get truthy value for each flattened field mock_args = dict( @@ -14909,19 +14948,20 @@ def test_delete_input_rest_flattened(): req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.delete_input(**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/*/inputs/*}" % client.transport._host, + "%s/v1/{name=projects/*/locations/*/channels/*}:start" + % client.transport._host, args[1], ) -def test_delete_input_rest_flattened_error(transport: str = "rest"): +def test_start_channel_rest_flattened_error(transport: str = "rest"): client = LivestreamServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -14930,13 +14970,13 @@ 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(), + client.start_channel( + service.StartChannelRequest(), name="name_value", ) -def test_update_input_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: @@ -14950,17 +14990,17 @@ def test_update_input_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.update_input 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.update_input] = mock_rpc + client._transport._wrapped_methods[client._transport.stop_channel] = mock_rpc request = {} - client.update_input(request) + client.stop_channel(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 @@ -14969,17 +15009,18 @@ def test_update_input_rest_use_cached_wrapped_rpc(): # subsequent calls should use the cached wrapper wrapper_fn.reset_mock() - client.update_input(request) + 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_update_input_rest_required_fields(request_type=service.UpdateInputRequest): +def test_stop_channel_rest_required_fields(request_type=service.StopChannelRequest): transport_class = transports.LivestreamServiceRestTransport request_init = {} + request_init["name"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -14990,24 +15031,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) + ).stop_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", - ) - ) + ).stop_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(), @@ -15028,7 +15066,7 @@ 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": "post", "query_params": pb_request, } transcode_result["body"] = pb_request @@ -15042,31 +15080,23 @@ def test_update_input_rest_required_fields(request_type=service.UpdateInputReque req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.update_input(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_update_input_rest_unset_required_fields(): +def test_stop_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.stop_channel._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) -def test_update_input_rest_flattened(): +def test_stop_channel_rest_flattened(): client = LivestreamServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -15078,14 +15108,11 @@ def test_update_input_rest_flattened(): return_value = operations_pb2.Operation(name="operations/spam") # 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) @@ -15097,20 +15124,20 @@ def test_update_input_rest_flattened(): req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.update_input(**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/{input.name=projects/*/locations/*/inputs/*}" + "%s/v1/{name=projects/*/locations/*/channels/*}:stop" % client.transport._host, args[1], ) -def test_update_input_rest_flattened_error(transport: str = "rest"): +def test_stop_channel_rest_flattened_error(transport: str = "rest"): client = LivestreamServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -15119,14 +15146,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.stop_channel( + service.StopChannelRequest(), + name="name_value", ) -def test_create_event_rest_use_cached_wrapped_rpc(): +def test_start_distribution_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -15140,34 +15166,43 @@ 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.start_distribution in client._transport._wrapped_methods + ) # Replace cached wrapped function with mock mock_rpc = 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.start_distribution + ] = mock_rpc request = {} - client.create_event(request) + client.start_distribution(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.start_distribution(request) # Establish 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_start_distribution_rest_required_fields( + request_type=service.StartDistributionRequest, +): 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( @@ -15175,37 +15210,24 @@ 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) + ).start_distribution._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) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set( - ( - "event_id", - "request_id", - ) - ) + ).start_distribution._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 "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(), @@ -15214,7 +15236,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 @@ -15234,52 +15256,29 @@ def test_create_event_rest_required_fields(request_type=service.CreateEventReque 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.start_distribution(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_start_distribution_rest_unset_required_fields(): transport = transports.LivestreamServiceRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.create_event._get_unset_required_fields({}) - assert set(unset_fields) == ( - set( - ( - "eventId", - "requestId", - ) - ) - & set( - ( - "parent", - "event", - "eventId", - ) - ) - ) + unset_fields = transport.start_distribution._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) -def test_create_event_rest_flattened(): +def test_start_distribution_rest_flattened(): client = LivestreamServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -15288,45 +15287,40 @@ 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", + distribution_keys=["distribution_keys_value"], ) mock_args.update(sample_request) # 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.start_distribution(**mock_args) # Establish that the underlying call was 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/{name=projects/*/locations/*/channels/*}:startdistribution" % client.transport._host, args[1], ) -def test_create_event_rest_flattened_error(transport: str = "rest"): +def test_start_distribution_rest_flattened_error(transport: str = "rest"): client = LivestreamServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -15335,15 +15329,14 @@ 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.start_distribution( + service.StartDistributionRequest(), + name="name_value", + distribution_keys=["distribution_keys_value"], ) -def test_list_events_rest_use_cached_wrapped_rpc(): +def test_stop_distribution_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -15357,33 +15350,41 @@ 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.stop_distribution in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = 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.stop_distribution + ] = mock_rpc request = {} - client.list_events(request) + client.stop_distribution(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.stop_distribution(request) # Establish 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_stop_distribution_rest_required_fields( + request_type=service.StopDistributionRequest, +): 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( @@ -15394,30 +15395,21 @@ 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) + ).stop_distribution._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_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", - ) - ) + ).stop_distribution._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(), @@ -15426,7 +15418,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 @@ -15438,49 +15430,37 @@ 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": "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.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.stop_distribution(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_stop_distribution_rest_unset_required_fields(): transport = transports.LivestreamServiceRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.list_events._get_unset_required_fields({}) - assert set(unset_fields) == ( - set( - ( - "filter", - "orderBy", - "pageSize", - "pageToken", - ) - ) - & set(("parent",)) - ) + unset_fields = transport.stop_distribution._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) -def test_list_events_rest_flattened(): +def test_stop_distribution_rest_flattened(): client = LivestreamServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -15489,43 +15469,40 @@ 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" - } + sample_request = {"name": "projects/sample1/locations/sample2/channels/sample3"} # get truthy value for each flattened field mock_args = dict( - parent="parent_value", + name="name_value", + distribution_keys=["distribution_keys_value"], ) mock_args.update(sample_request) # 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.stop_distribution(**mock_args) # Establish that the underlying call was 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/{name=projects/*/locations/*/channels/*}:stopdistribution" % client.transport._host, args[1], ) -def test_list_events_rest_flattened_error(transport: str = "rest"): +def test_stop_distribution_rest_flattened_error(transport: str = "rest"): client = LivestreamServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -15534,76 +15511,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.stop_distribution( + service.StopDistributionRequest(), + name="name_value", + distribution_keys=["distribution_keys_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_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: @@ -15617,33 +15532,38 @@ 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.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.get_event] = mock_rpc + client._transport._wrapped_methods[client._transport.create_input] = mock_rpc request = {} - client.get_event(request) + client.create_input(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.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_get_event_rest_required_fields(request_type=service.GetEventRequest): +def test_create_input_rest_required_fields(request_type=service.CreateInputRequest): transport_class = transports.LivestreamServiceRestTransport request_init = {} - request_init["name"] = "" + request_init["parent"] = "" + request_init["input_id"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -15651,24 +15571,37 @@ def test_get_event_rest_required_fields(request_type=service.GetEventRequest): ) # verify fields with default values are dropped + assert "inputId" not in jsonified_request unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).get_event._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["name"] = "name_value" + jsonified_request["parent"] = "parent_value" + jsonified_request["inputId"] = "input_id_value" unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).get_event._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) + ).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 "name" in jsonified_request - assert jsonified_request["name"] == "name_value" + 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(), @@ -15677,7 +15610,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 @@ -15689,39 +15622,57 @@ 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.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_get_event_rest_unset_required_fields(): +def test_create_input_rest_unset_required_fields(): transport = transports.LivestreamServiceRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.get_event._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name",))) + unset_fields = transport.create_input._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "inputId", + "requestId", + ) + ) + & set( + ( + "parent", + "input", + "inputId", + ) + ) + ) -def test_get_event_rest_flattened(): +def test_create_input_rest_flattened(): client = LivestreamServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -15730,43 +15681,40 @@ 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 = {"parent": "projects/sample1/locations/sample2"} # get truthy value for each flattened field mock_args = dict( - name="name_value", + 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 = 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.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/{name=projects/*/locations/*/channels/*/events/*}" - % client.transport._host, + "%s/v1/{parent=projects/*/locations/*}/inputs" % client.transport._host, args[1], ) -def test_get_event_rest_flattened_error(transport: str = "rest"): +def test_create_input_rest_flattened_error(transport: str = "rest"): client = LivestreamServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -15775,13 +15723,15 @@ 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(), - name="name_value", + client.create_input( + service.CreateInputRequest(), + parent="parent_value", + input=resources.Input(name="name_value"), + input_id="input_id_value", ) -def test_delete_event_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: @@ -15795,33 +15745,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.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.delete_event] = mock_rpc + client._transport._wrapped_methods[client._transport.list_inputs] = mock_rpc request = {} - client.delete_event(request) + client.list_inputs(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.delete_event(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_delete_event_rest_required_fields(request_type=service.DeleteEventRequest): +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( @@ -15832,23 +15782,30 @@ 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) + ).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() - ).delete_event._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(("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(), @@ -15857,7 +15814,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 = 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 @@ -15869,36 +15826,49 @@ 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": "get", "query_params": pb_request, } transcode.return_value = transcode_result response_value = Response() response_value.status_code = 200 - json_return_value = "" + + # Convert return value to protobuf type + return_value = 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_event(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_delete_event_rest_unset_required_fields(): +def test_list_inputs_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.list_inputs._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "filter", + "orderBy", + "pageSize", + "pageToken", + ) + ) + & set(("parent",)) + ) -def test_delete_event_rest_flattened(): +def test_list_inputs_rest_flattened(): client = LivestreamServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -15907,41 +15877,40 @@ 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 = service.ListInputsResponse() # get arguments that satisfy an http rule for this method - sample_request = { - "name": "projects/sample1/locations/sample2/channels/sample3/events/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) # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 - json_return_value = "" + # Convert return value to protobuf type + return_value = 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.delete_event(**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/*/events/*}" - % client.transport._host, + "%s/v1/{parent=projects/*/locations/*}/inputs" % client.transport._host, args[1], ) -def test_delete_event_rest_flattened_error(transport: str = "rest"): +def test_list_inputs_rest_flattened_error(transport: str = "rest"): client = LivestreamServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -15950,13 +15919,74 @@ 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(), - name="name_value", + client.list_inputs( + service.ListInputsRequest(), + parent="parent_value", ) -def test_list_clips_rest_use_cached_wrapped_rpc(): +def test_list_inputs_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.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 + + # 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 + + 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: @@ -15970,33 +16000,33 @@ 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.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.list_clips] = mock_rpc + client._transport._wrapped_methods[client._transport.get_input] = mock_rpc request = {} - client.list_clips(request) + client.get_input(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.list_clips(request) + 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_list_clips_rest_required_fields(request_type=service.ListClipsRequest): +def test_get_input_rest_required_fields(request_type=service.GetInputRequest): 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( @@ -16007,30 +16037,21 @@ def test_list_clips_rest_required_fields(request_type=service.ListClipsRequest): unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).list_clips._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 - jsonified_request["parent"] = "parent_value" + jsonified_request["name"] = "name_value" unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).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( - ( - "filter", - "order_by", - "page_size", - "page_token", - ) - ) + ).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 "name" in jsonified_request + assert jsonified_request["name"] == "name_value" client = LivestreamServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -16039,7 +16060,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 = 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 @@ -16060,40 +16081,30 @@ def test_list_clips_rest_required_fields(request_type=service.ListClipsRequest): response_value.status_code = 200 # Convert return value to protobuf type - return_value = service.ListClipsResponse.pb(return_value) + 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.list_clips(request) + response = client.get_input(request) expected_params = [("$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_get_input_rest_unset_required_fields(): transport = transports.LivestreamServiceRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.list_clips._get_unset_required_fields({}) - assert set(unset_fields) == ( - set( - ( - "filter", - "orderBy", - "pageSize", - "pageToken", - ) - ) - & set(("parent",)) - ) + unset_fields = transport.get_input._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) -def test_list_clips_rest_flattened(): +def test_get_input_rest_flattened(): client = LivestreamServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -16102,16 +16113,14 @@ 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 = 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", + name="name_value", ) mock_args.update(sample_request) @@ -16119,26 +16128,25 @@ def test_list_clips_rest_flattened(): response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = service.ListClipsResponse.pb(return_value) + 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.list_clips(**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_list_clips_rest_flattened_error(transport: str = "rest"): +def test_get_input_rest_flattened_error(transport: str = "rest"): client = LivestreamServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -16147,76 +16155,13 @@ 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(), - parent="parent_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(), - ], - ), + client.get_input( + service.GetInputRequest(), + name="name_value", ) - # 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_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: @@ -16230,29 +16175,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.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.get_clip] = mock_rpc + client._transport._wrapped_methods[client._transport.delete_input] = mock_rpc request = {} - client.get_clip(request) + client.delete_input(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.get_clip(request) + # 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) # Establish 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_delete_input_rest_required_fields(request_type=service.DeleteInputRequest): transport_class = transports.LivestreamServiceRestTransport request_init = {} @@ -16267,7 +16216,7 @@ 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) + ).delete_input._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present @@ -16276,7 +16225,9 @@ 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) + ).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) # verify required fields with non-default values are left alone @@ -16290,7 +16241,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 = 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 @@ -16302,39 +16253,36 @@ def test_get_clip_rest_required_fields(request_type=service.GetClipRequest): 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.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.get_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_get_clip_rest_unset_required_fields(): +def test_delete_input_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.delete_input._get_unset_required_fields({}) + assert set(unset_fields) == (set(("requestId",)) & set(("name",))) -def test_get_clip_rest_flattened(): +def test_delete_input_rest_flattened(): client = LivestreamServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -16343,12 +16291,10 @@ 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 = 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( @@ -16359,27 +16305,24 @@ def test_get_clip_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.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"} - client.get_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_get_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, @@ -16388,13 +16331,13 @@ 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(), + client.delete_input( + service.DeleteInputRequest(), name="name_value", ) -def test_create_clip_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: @@ -16408,17 +16351,17 @@ def test_create_clip_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.create_clip 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_clip] = mock_rpc + client._transport._wrapped_methods[client._transport.update_input] = mock_rpc request = {} - client.create_clip(request) + client.update_input(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 @@ -16427,19 +16370,17 @@ def test_create_clip_rest_use_cached_wrapped_rpc(): # subsequent calls should use the cached wrapper wrapper_fn.reset_mock() - client.create_clip(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_clip_rest_required_fields(request_type=service.CreateClipRequest): +def test_update_input_rest_required_fields(request_type=service.UpdateInputRequest): transport_class = transports.LivestreamServiceRestTransport request_init = {} - request_init["parent"] = "" - request_init["clip_id"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -16447,37 +16388,27 @@ 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) + ).update_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" unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).create_clip._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( ( - "clip_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 "clipId" in jsonified_request - assert jsonified_request["clipId"] == "clip_id_value" client = LivestreamServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -16498,7 +16429,7 @@ 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": "patch", "query_params": pb_request, } transcode_result["body"] = pb_request @@ -16512,43 +16443,31 @@ def test_create_clip_rest_required_fields(request_type=service.CreateClipRequest req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.create_clip(request) + response = client.update_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_update_input_rest_unset_required_fields(): transport = transports.LivestreamServiceRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.create_clip._get_unset_required_fields({}) + unset_fields = transport.update_input._get_unset_required_fields({}) assert set(unset_fields) == ( set( ( - "clipId", "requestId", + "updateMask", ) ) - & set( - ( - "parent", - "clipId", - "clip", - ) - ) + & set(("input",)) ) -def test_create_clip_rest_flattened(): +def test_update_input_rest_flattened(): client = LivestreamServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -16561,14 +16480,13 @@ def test_create_clip_rest_flattened(): # get arguments that satisfy an http rule for this method sample_request = { - "parent": "projects/sample1/locations/sample2/channels/sample3" + "input": {"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", + input=resources.Input(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) mock_args.update(sample_request) @@ -16580,20 +16498,20 @@ def test_create_clip_rest_flattened(): req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.create_clip(**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/*/channels/*}/clips" + "%s/v1/{input.name=projects/*/locations/*/inputs/*}" % client.transport._host, args[1], ) -def test_create_clip_rest_flattened_error(transport: str = "rest"): +def test_update_input_rest_flattened_error(transport: str = "rest"): client = LivestreamServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -16602,15 +16520,14 @@ 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.update_input( + service.UpdateInputRequest(), + input=resources.Input(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) -def test_delete_clip_rest_use_cached_wrapped_rpc(): +def test_preview_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: @@ -16624,33 +16541,29 @@ 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.preview_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.preview_input] = mock_rpc request = {} - client.delete_clip(request) + client.preview_input(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_clip(request) + client.preview_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_preview_input_rest_required_fields(request_type=service.PreviewInputRequest): transport_class = transports.LivestreamServiceRestTransport request_init = {} @@ -16665,7 +16578,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) + ).preview_input._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present @@ -16674,9 +16587,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) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("request_id",)) + ).preview_input._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone @@ -16690,7 +16601,7 @@ def test_delete_clip_rest_required_fields(request_type=service.DeleteClipRequest request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name="operations/spam") + return_value = service.PreviewInputResponse() # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values @@ -16702,36 +16613,40 @@ def test_delete_clip_rest_required_fields(request_type=service.DeleteClipRequest 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 = service.PreviewInputResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_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.preview_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_preview_input_rest_unset_required_fields(): transport = transports.LivestreamServiceRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.delete_clip._get_unset_required_fields({}) - assert set(unset_fields) == (set(("requestId",)) & set(("name",))) + unset_fields = transport.preview_input._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) -def test_delete_clip_rest_flattened(): +def test_preview_input_rest_flattened(): client = LivestreamServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -16740,12 +16655,10 @@ def test_delete_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 = service.PreviewInputResponse() # 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( @@ -16756,25 +16669,27 @@ def test_delete_clip_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 = service.PreviewInputResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = 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_clip(**mock_args) + client.preview_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/*}" + "%s/v1/{name=projects/*/locations/*/inputs/*}:preview" % client.transport._host, args[1], ) -def test_delete_clip_rest_flattened_error(transport: str = "rest"): +def test_preview_input_rest_flattened_error(transport: str = "rest"): client = LivestreamServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -16783,13 +16698,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.preview_input( + service.PreviewInputRequest(), name="name_value", ) -def test_create_dvr_session_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: @@ -16803,44 +16718,34 @@ def test_create_dvr_session_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert ( - client._transport.create_dvr_session 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.create_dvr_session - ] = mock_rpc + client._transport._wrapped_methods[client._transport.create_event] = mock_rpc request = {} - client.create_dvr_session(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.create_dvr_session(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_create_dvr_session_rest_required_fields( - request_type=service.CreateDvrSessionRequest, -): +def test_create_event_rest_required_fields(request_type=service.CreateEventRequest): transport_class = transports.LivestreamServiceRestTransport request_init = {} request_init["parent"] = "" - request_init["dvr_session_id"] = "" + request_init["event_id"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -16848,27 +16753,27 @@ def test_create_dvr_session_rest_required_fields( ) # verify fields with default values are dropped - assert "dvrSessionId" not in jsonified_request + assert "eventId" not in jsonified_request unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).create_dvr_session._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 "dvrSessionId" in jsonified_request - assert jsonified_request["dvrSessionId"] == request_init["dvr_session_id"] + assert "eventId" in jsonified_request + assert jsonified_request["eventId"] == request_init["event_id"] jsonified_request["parent"] = "parent_value" - jsonified_request["dvrSessionId"] = "dvr_session_id_value" + jsonified_request["eventId"] = "event_id_value" unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).create_dvr_session._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( ( - "dvr_session_id", + "event_id", "request_id", ) ) @@ -16877,8 +16782,8 @@ def test_create_dvr_session_rest_required_fields( # 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 "eventId" in jsonified_request + assert jsonified_request["eventId"] == "event_id_value" client = LivestreamServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -16887,7 +16792,7 @@ def test_create_dvr_session_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name="operations/spam") + return_value = 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 @@ -16907,17 +16812,20 @@ def test_create_dvr_session_rest_required_fields( 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_dvr_session(request) + response = client.create_event(request) expected_params = [ ( - "dvrSessionId", + "eventId", "", ), ("$alt", "json;enum-encoding=int"), @@ -16926,30 +16834,30 @@ def test_create_dvr_session_rest_required_fields( assert expected_params == actual_params -def test_create_dvr_session_rest_unset_required_fields(): +def test_create_event_rest_unset_required_fields(): transport = transports.LivestreamServiceRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.create_dvr_session._get_unset_required_fields({}) + unset_fields = transport.create_event._get_unset_required_fields({}) assert set(unset_fields) == ( set( ( - "dvrSessionId", + "eventId", "requestId", ) ) & set( ( "parent", - "dvrSessionId", - "dvrSession", + "event", + "eventId", ) ) ) -def test_create_dvr_session_rest_flattened(): +def test_create_event_rest_flattened(): client = LivestreamServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -16958,7 +16866,7 @@ def test_create_dvr_session_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 = { @@ -16968,33 +16876,35 @@ def test_create_dvr_session_rest_flattened(): # 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", + 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.create_dvr_session(**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/{parent=projects/*/locations/*/channels/*}/dvrSessions" + "%s/v1/{parent=projects/*/locations/*/channels/*}/events" % client.transport._host, args[1], ) -def test_create_dvr_session_rest_flattened_error(transport: str = "rest"): +def test_create_event_rest_flattened_error(transport: str = "rest"): client = LivestreamServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -17003,15 +16913,15 @@ def test_create_dvr_session_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_dvr_session( - service.CreateDvrSessionRequest(), + client.create_event( + service.CreateEventRequest(), parent="parent_value", - dvr_session=resources.DvrSession(name="name_value"), - dvr_session_id="dvr_session_id_value", + event=resources.Event(name="name_value"), + event_id="event_id_value", ) -def test_list_dvr_sessions_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: @@ -17025,33 +16935,29 @@ def test_list_dvr_sessions_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.list_dvr_sessions 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.list_dvr_sessions - ] = mock_rpc + client._transport._wrapped_methods[client._transport.list_events] = mock_rpc request = {} - client.list_dvr_sessions(request) + client.list_events(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.list_dvr_sessions(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_list_dvr_sessions_rest_required_fields( - request_type=service.ListDvrSessionsRequest, -): +def test_list_events_rest_required_fields(request_type=service.ListEventsRequest): transport_class = transports.LivestreamServiceRestTransport request_init = {} @@ -17066,7 +16972,7 @@ def test_list_dvr_sessions_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).list_dvr_sessions._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 @@ -17075,7 +16981,7 @@ def test_list_dvr_sessions_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).list_dvr_sessions._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( ( @@ -17098,7 +17004,7 @@ def test_list_dvr_sessions_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = service.ListDvrSessionsResponse() + 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 @@ -17119,26 +17025,26 @@ def test_list_dvr_sessions_rest_required_fields( response_value.status_code = 200 # Convert return value to protobuf type - return_value = service.ListDvrSessionsResponse.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_dvr_sessions(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_list_dvr_sessions_rest_unset_required_fields(): +def test_list_events_rest_unset_required_fields(): transport = transports.LivestreamServiceRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.list_dvr_sessions._get_unset_required_fields({}) + unset_fields = transport.list_events._get_unset_required_fields({}) assert set(unset_fields) == ( set( ( @@ -17152,7 +17058,7 @@ def test_list_dvr_sessions_rest_unset_required_fields(): ) -def test_list_dvr_sessions_rest_flattened(): +def test_list_events_rest_flattened(): client = LivestreamServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -17161,7 +17067,7 @@ def test_list_dvr_sessions_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.ListDvrSessionsResponse() + return_value = service.ListEventsResponse() # get arguments that satisfy an http rule for this method sample_request = { @@ -17178,26 +17084,26 @@ def test_list_dvr_sessions_rest_flattened(): response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = service.ListDvrSessionsResponse.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.list_dvr_sessions(**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/{parent=projects/*/locations/*/channels/*}/dvrSessions" + "%s/v1/{parent=projects/*/locations/*/channels/*}/events" % client.transport._host, args[1], ) -def test_list_dvr_sessions_rest_flattened_error(transport: str = "rest"): +def test_list_events_rest_flattened_error(transport: str = "rest"): client = LivestreamServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -17206,13 +17112,13 @@ def test_list_dvr_sessions_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_dvr_sessions( - service.ListDvrSessionsRequest(), + client.list_events( + service.ListEventsRequest(), parent="parent_value", ) -def test_list_dvr_sessions_rest_pager(transport: str = "rest"): +def test_list_events_rest_pager(transport: str = "rest"): client = LivestreamServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -17224,28 +17130,28 @@ def test_list_dvr_sessions_rest_pager(transport: str = "rest"): # 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(), + service.ListEventsResponse( + events=[ + resources.Event(), + resources.Event(), + resources.Event(), ], next_page_token="abc", ), - service.ListDvrSessionsResponse( - dvr_sessions=[], + service.ListEventsResponse( + events=[], next_page_token="def", ), - service.ListDvrSessionsResponse( - dvr_sessions=[ - resources.DvrSession(), + service.ListEventsResponse( + events=[ + resources.Event(), ], next_page_token="ghi", ), - service.ListDvrSessionsResponse( - dvr_sessions=[ - resources.DvrSession(), - resources.DvrSession(), + service.ListEventsResponse( + events=[ + resources.Event(), + resources.Event(), ], ), ) @@ -17253,7 +17159,7 @@ def test_list_dvr_sessions_rest_pager(transport: str = "rest"): response = response + response # Wrap the values into proper Response objs - response = tuple(service.ListDvrSessionsResponse.to_json(x) for x in response) + 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") @@ -17264,18 +17170,18 @@ def test_list_dvr_sessions_rest_pager(transport: str = "rest"): "parent": "projects/sample1/locations/sample2/channels/sample3" } - pager = client.list_dvr_sessions(request=sample_request) + pager = client.list_events(request=sample_request) results = list(pager) assert len(results) == 6 - assert all(isinstance(i, resources.DvrSession) for i in results) + assert all(isinstance(i, resources.Event) for i in results) - pages = list(client.list_dvr_sessions(request=sample_request).pages) + 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_dvr_session_rest_use_cached_wrapped_rpc(): +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: @@ -17289,31 +17195,29 @@ def test_get_dvr_session_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.get_dvr_session in client._transport._wrapped_methods + 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.get_dvr_session] = mock_rpc + client._transport._wrapped_methods[client._transport.get_event] = mock_rpc request = {} - client.get_dvr_session(request) + client.get_event(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.get_dvr_session(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_get_dvr_session_rest_required_fields( - request_type=service.GetDvrSessionRequest, -): +def test_get_event_rest_required_fields(request_type=service.GetEventRequest): transport_class = transports.LivestreamServiceRestTransport request_init = {} @@ -17328,7 +17232,7 @@ def test_get_dvr_session_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).get_dvr_session._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 @@ -17337,7 +17241,7 @@ def test_get_dvr_session_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).get_dvr_session._get_unset_required_fields(jsonified_request) + ).get_event._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone @@ -17351,7 +17255,7 @@ def test_get_dvr_session_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = resources.DvrSession() + 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 @@ -17372,30 +17276,30 @@ def test_get_dvr_session_rest_required_fields( response_value.status_code = 200 # Convert return value to protobuf type - return_value = resources.DvrSession.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.get_dvr_session(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_get_dvr_session_rest_unset_required_fields(): +def test_get_event_rest_unset_required_fields(): transport = transports.LivestreamServiceRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.get_dvr_session._get_unset_required_fields({}) + unset_fields = transport.get_event._get_unset_required_fields({}) assert set(unset_fields) == (set(()) & set(("name",))) -def test_get_dvr_session_rest_flattened(): +def test_get_event_rest_flattened(): client = LivestreamServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -17404,11 +17308,11 @@ def test_get_dvr_session_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.DvrSession() + return_value = resources.Event() # get arguments that satisfy an http rule for this method sample_request = { - "name": "projects/sample1/locations/sample2/channels/sample3/dvrSessions/sample4" + "name": "projects/sample1/locations/sample2/channels/sample3/events/sample4" } # get truthy value for each flattened field @@ -17421,26 +17325,26 @@ def test_get_dvr_session_rest_flattened(): response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = resources.DvrSession.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.get_dvr_session(**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/{name=projects/*/locations/*/channels/*/dvrSessions/*}" + "%s/v1/{name=projects/*/locations/*/channels/*/events/*}" % client.transport._host, args[1], ) -def test_get_dvr_session_rest_flattened_error(transport: str = "rest"): +def test_get_event_rest_flattened_error(transport: str = "rest"): client = LivestreamServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -17449,13 +17353,13 @@ def test_get_dvr_session_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_dvr_session( - service.GetDvrSessionRequest(), + client.get_event( + service.GetEventRequest(), name="name_value", ) -def test_delete_dvr_session_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: @@ -17469,39 +17373,29 @@ def test_delete_dvr_session_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert ( - client._transport.delete_dvr_session 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.delete_dvr_session - ] = mock_rpc + client._transport._wrapped_methods[client._transport.delete_event] = mock_rpc request = {} - client.delete_dvr_session(request) + client.delete_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_dvr_session(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_delete_dvr_session_rest_required_fields( - request_type=service.DeleteDvrSessionRequest, -): +def test_delete_event_rest_required_fields(request_type=service.DeleteEventRequest): transport_class = transports.LivestreamServiceRestTransport request_init = {} @@ -17516,7 +17410,7 @@ def test_delete_dvr_session_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).delete_dvr_session._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 @@ -17525,7 +17419,7 @@ def test_delete_dvr_session_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).delete_dvr_session._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) @@ -17541,7 +17435,7 @@ def test_delete_dvr_session_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name="operations/spam") + return_value = 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 @@ -17560,29 +17454,29 @@ def test_delete_dvr_session_rest_required_fields( response_value = Response() response_value.status_code = 200 - 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.delete_dvr_session(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_delete_dvr_session_rest_unset_required_fields(): +def test_delete_event_rest_unset_required_fields(): transport = transports.LivestreamServiceRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.delete_dvr_session._get_unset_required_fields({}) + unset_fields = transport.delete_event._get_unset_required_fields({}) assert set(unset_fields) == (set(("requestId",)) & set(("name",))) -def test_delete_dvr_session_rest_flattened(): +def test_delete_event_rest_flattened(): client = LivestreamServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -17591,11 +17485,11 @@ def test_delete_dvr_session_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 = None # get arguments that satisfy an http rule for this method sample_request = { - "name": "projects/sample1/locations/sample2/channels/sample3/dvrSessions/sample4" + "name": "projects/sample1/locations/sample2/channels/sample3/events/sample4" } # get truthy value for each flattened field @@ -17607,25 +17501,25 @@ def test_delete_dvr_session_rest_flattened(): # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 - 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.delete_dvr_session(**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/*/channels/*/dvrSessions/*}" + "%s/v1/{name=projects/*/locations/*/channels/*/events/*}" % client.transport._host, args[1], ) -def test_delete_dvr_session_rest_flattened_error(transport: str = "rest"): +def test_delete_event_rest_flattened_error(transport: str = "rest"): client = LivestreamServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -17634,13 +17528,13 @@ def test_delete_dvr_session_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_dvr_session( - service.DeleteDvrSessionRequest(), + client.delete_event( + service.DeleteEventRequest(), name="name_value", ) -def test_update_dvr_session_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: @@ -17654,42 +17548,33 @@ def test_update_dvr_session_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert ( - client._transport.update_dvr_session 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_dvr_session - ] = mock_rpc + client._transport._wrapped_methods[client._transport.list_clips] = mock_rpc request = {} - client.update_dvr_session(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_dvr_session(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_dvr_session_rest_required_fields( - request_type=service.UpdateDvrSessionRequest, -): +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( @@ -17700,24 +17585,30 @@ def test_update_dvr_session_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).update_dvr_session._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_dvr_session._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(), @@ -17726,7 +17617,7 @@ def test_update_dvr_session_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name="operations/spam") + return_value = 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 @@ -17738,50 +17629,49 @@ def test_update_dvr_session_rest_required_fields( pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "patch", + "method": "get", "query_params": pb_request, } - transcode_result["body"] = pb_request transcode.return_value = transcode_result response_value = Response() response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = 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_dvr_session(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_dvr_session_rest_unset_required_fields(): +def test_list_clips_rest_unset_required_fields(): transport = transports.LivestreamServiceRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.update_dvr_session._get_unset_required_fields({}) + unset_fields = transport.list_clips._get_unset_required_fields({}) assert set(unset_fields) == ( set( ( - "requestId", - "updateMask", - ) - ) - & set( - ( - "updateMask", - "dvrSession", + "filter", + "orderBy", + "pageSize", + "pageToken", ) ) + & set(("parent",)) ) -def test_update_dvr_session_rest_flattened(): +def test_list_clips_rest_flattened(): client = LivestreamServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -17790,44 +17680,43 @@ def test_update_dvr_session_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 = { - "dvr_session": { - "name": "projects/sample1/locations/sample2/channels/sample3/dvrSessions/sample4" - } + "parent": "projects/sample1/locations/sample2/channels/sample3" } # 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"]), + 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_dvr_session(**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/{dvr_session.name=projects/*/locations/*/channels/*/dvrSessions/*}" + "%s/v1/{parent=projects/*/locations/*/channels/*}/clips" % client.transport._host, args[1], ) -def test_update_dvr_session_rest_flattened_error(transport: str = "rest"): +def test_list_clips_rest_flattened_error(transport: str = "rest"): client = LivestreamServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -17836,14 +17725,76 @@ def test_update_dvr_session_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_dvr_session( - service.UpdateDvrSessionRequest(), - dvr_session=resources.DvrSession(name="name_value"), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + client.list_clips( + service.ListClipsRequest(), + parent="parent_value", ) -def test_create_asset_rest_use_cached_wrapped_rpc(): +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(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -17857,38 +17808,33 @@ 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.get_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_asset] = mock_rpc + client._transport._wrapped_methods[client._transport.get_clip] = mock_rpc request = {} - client.create_asset(request) + client.get_clip(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) + client.get_clip(request) # Establish 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_get_clip_rest_required_fields(request_type=service.GetClipRequest): transport_class = transports.LivestreamServiceRestTransport request_init = {} - request_init["parent"] = "" - request_init["asset_id"] = "" + request_init["name"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -17896,37 +17842,24 @@ 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) + ).get_clip._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" + jsonified_request["name"] = "name_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", - ) - ) + ).get_clip._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 "assetId" in jsonified_request - assert jsonified_request["assetId"] == "asset_id_value" + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" client = LivestreamServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -17935,7 +17868,7 @@ def test_create_asset_rest_required_fields(request_type=service.CreateAssetReque request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name="operations/spam") + 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 @@ -17947,57 +17880,39 @@ 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": "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.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.create_asset(request) + response = client.get_clip(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_get_clip_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", - ) - ) - ) + unset_fields = transport.get_clip._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) -def test_create_asset_rest_flattened(): +def test_get_clip_rest_flattened(): client = LivestreamServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -18006,40 +17921,43 @@ def test_create_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.Clip() # 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/clips/sample4" + } # get truthy value for each flattened field mock_args = dict( - parent="parent_value", - asset=resources.Asset(name="name_value"), - asset_id="asset_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.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"} - client.create_asset(**mock_args) + client.get_clip(**mock_args) # Establish that the underlying call was 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/*/clips/*}" + % client.transport._host, args[1], ) -def test_create_asset_rest_flattened_error(transport: str = "rest"): +def test_get_clip_rest_flattened_error(transport: str = "rest"): client = LivestreamServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -18048,15 +17966,13 @@ 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.get_clip( + service.GetClipRequest(), + name="name_value", ) -def test_delete_asset_rest_use_cached_wrapped_rpc(): +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: @@ -18070,17 +17986,17 @@ 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_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.delete_asset] = mock_rpc + client._transport._wrapped_methods[client._transport.create_clip] = mock_rpc request = {} - client.delete_asset(request) + client.create_clip(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 @@ -18089,18 +18005,19 @@ def test_delete_asset_rest_use_cached_wrapped_rpc(): # subsequent calls should use the cached wrapper wrapper_fn.reset_mock() - client.delete_asset(request) + client.create_clip(request) # Establish 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_clip_rest_required_fields(request_type=service.CreateClipRequest): transport_class = transports.LivestreamServiceRestTransport request_init = {} - request_init["name"] = "" + request_init["parent"] = "" + request_init["clip_id"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -18108,26 +18025,37 @@ def test_delete_asset_rest_required_fields(request_type=service.DeleteAssetReque ) # verify fields with default values are dropped + assert "clipId" not in jsonified_request unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).delete_asset._get_unset_required_fields(jsonified_request) + ).create_clip._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["name"] = "name_value" + jsonified_request["parent"] = "parent_value" + jsonified_request["clipId"] = "clip_id_value" unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).delete_asset._get_unset_required_fields(jsonified_request) + ).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(("request_id",)) + assert not set(unset_fields) - set( + ( + "clip_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 "clipId" in jsonified_request + assert jsonified_request["clipId"] == "clip_id_value" client = LivestreamServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -18148,9 +18076,10 @@ 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() @@ -18161,23 +18090,43 @@ def test_delete_asset_rest_required_fields(request_type=service.DeleteAssetReque 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_clip(request) - expected_params = [("$alt", "json;enum-encoding=int")] + expected_params = [ + ( + "clipId", + "", + ), + ("$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_clip_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_clip._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "clipId", + "requestId", + ) + ) + & set( + ( + "parent", + "clipId", + "clip", + ) + ) + ) -def test_delete_asset_rest_flattened(): +def test_create_clip_rest_flattened(): client = LivestreamServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -18189,11 +18138,15 @@ def test_delete_asset_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/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", + clip=resources.Clip(name="name_value"), + clip_id="clip_id_value", ) mock_args.update(sample_request) @@ -18205,19 +18158,20 @@ def test_delete_asset_rest_flattened(): req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.delete_asset(**mock_args) + client.create_clip(**mock_args) # Establish that the underlying call was 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/*}/clips" + % client.transport._host, args[1], ) -def test_delete_asset_rest_flattened_error(transport: str = "rest"): +def test_create_clip_rest_flattened_error(transport: str = "rest"): client = LivestreamServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -18226,13 +18180,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_clip( + service.CreateClipRequest(), + parent="parent_value", + clip=resources.Clip(name="name_value"), + clip_id="clip_id_value", ) -def test_get_asset_rest_use_cached_wrapped_rpc(): +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: @@ -18246,29 +18202,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.delete_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.get_asset] = mock_rpc + client._transport._wrapped_methods[client._transport.delete_clip] = mock_rpc request = {} - client.get_asset(request) + client.delete_clip(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.get_asset(request) + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.delete_clip(request) # Establish 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_delete_clip_rest_required_fields(request_type=service.DeleteClipRequest): transport_class = transports.LivestreamServiceRestTransport request_init = {} @@ -18283,7 +18243,7 @@ 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) + ).delete_clip._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present @@ -18292,7 +18252,9 @@ 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) + ).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 @@ -18306,7 +18268,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 = 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 @@ -18318,39 +18280,36 @@ def test_get_asset_rest_required_fields(request_type=service.GetAssetRequest): 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.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) + response = client.delete_clip(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_delete_clip_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.delete_clip._get_unset_required_fields({}) + assert set(unset_fields) == (set(("requestId",)) & set(("name",))) -def test_get_asset_rest_flattened(): +def test_delete_clip_rest_flattened(): client = LivestreamServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -18359,10 +18318,12 @@ 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 = 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"} + sample_request = { + "name": "projects/sample1/locations/sample2/channels/sample3/clips/sample4" + } # get truthy value for each flattened field mock_args = dict( @@ -18373,26 +18334,25 @@ def test_get_asset_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.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) + client.delete_clip(**mock_args) # Establish that the underlying call was 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/{name=projects/*/locations/*/channels/*/clips/*}" + % client.transport._host, args[1], ) -def test_get_asset_rest_flattened_error(transport: str = "rest"): +def test_delete_clip_rest_flattened_error(transport: str = "rest"): client = LivestreamServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -18401,13 +18361,13 @@ 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(), + client.delete_clip( + service.DeleteClipRequest(), name="name_value", ) -def test_list_assets_rest_use_cached_wrapped_rpc(): +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: @@ -18421,33 +18381,44 @@ def test_list_assets_rest_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.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.list_assets] = mock_rpc + client._transport._wrapped_methods[ + client._transport.create_dvr_session + ] = mock_rpc request = {} - client.list_assets(request) + client.create_dvr_session(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.list_assets(request) + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.create_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_list_assets_rest_required_fields(request_type=service.ListAssetsRequest): +def test_create_dvr_session_rest_required_fields( + request_type=service.CreateDvrSessionRequest, +): transport_class = transports.LivestreamServiceRestTransport 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( @@ -18455,26 +18426,28 @@ def test_list_assets_rest_required_fields(request_type=service.ListAssetsRequest ) # verify fields with default values are dropped + assert "dvrSessionId" not in jsonified_request unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).list_assets._get_unset_required_fields(jsonified_request) + ).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"] jsonified_request["parent"] = "parent_value" + jsonified_request["dvrSessionId"] = "dvr_session_id_value" unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).list_assets._get_unset_required_fields(jsonified_request) + ).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( ( - "filter", - "order_by", - "page_size", - "page_token", + "dvr_session_id", + "request_id", ) ) jsonified_request.update(unset_fields) @@ -18482,6 +18455,8 @@ def test_list_assets_rest_required_fields(request_type=service.ListAssetsRequest # 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" client = LivestreamServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -18490,7 +18465,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 = 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 @@ -18502,49 +18477,57 @@ def test_list_assets_rest_required_fields(request_type=service.ListAssetsRequest 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.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) + response = client.create_dvr_session(request) - expected_params = [("$alt", "json;enum-encoding=int")] + expected_params = [ + ( + "dvrSessionId", + "", + ), + ("$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_create_dvr_session_rest_unset_required_fields(): transport = transports.LivestreamServiceRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.list_assets._get_unset_required_fields({}) + unset_fields = transport.create_dvr_session._get_unset_required_fields({}) assert set(unset_fields) == ( set( ( - "filter", - "orderBy", - "pageSize", - "pageToken", + "dvrSessionId", + "requestId", + ) + ) + & set( + ( + "parent", + "dvrSessionId", + "dvrSession", ) ) - & set(("parent",)) ) -def test_list_assets_rest_flattened(): +def test_create_dvr_session_rest_flattened(): client = LivestreamServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -18553,40 +18536,43 @@ 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 = 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 = { + "parent": "projects/sample1/locations/sample2/channels/sample3" + } # 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", ) mock_args.update(sample_request) # 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) + 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/*}/assets" % client.transport._host, + "%s/v1/{parent=projects/*/locations/*/channels/*}/dvrSessions" + % client.transport._host, args[1], ) -def test_list_assets_rest_flattened_error(transport: str = "rest"): +def test_create_dvr_session_rest_flattened_error(transport: str = "rest"): client = LivestreamServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -18595,74 +18581,15 @@ 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(), + client.create_dvr_session( + service.CreateDvrSessionRequest(), parent="parent_value", + dvr_session=resources.DvrSession(name="name_value"), + dvr_session_id="dvr_session_id_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(): +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: @@ -18676,33 +18603,37 @@ 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.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.get_pool] = mock_rpc + client._transport._wrapped_methods[ + client._transport.list_dvr_sessions + ] = mock_rpc request = {} - client.get_pool(request) + client.list_dvr_sessions(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.get_pool(request) + client.list_dvr_sessions(request) # Establish 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_list_dvr_sessions_rest_required_fields( + request_type=service.ListDvrSessionsRequest, +): 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( @@ -18713,21 +18644,30 @@ 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) + ).list_dvr_sessions._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_pool._get_unset_required_fields(jsonified_request) + ).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) # 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(), @@ -18736,7 +18676,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 = 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 @@ -18757,30 +18697,40 @@ def test_get_pool_rest_required_fields(request_type=service.GetPoolRequest): response_value.status_code = 200 # Convert return value to protobuf type - return_value = resources.Pool.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.get_pool(request) + response = client.list_dvr_sessions(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_list_dvr_sessions_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.list_dvr_sessions._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "filter", + "orderBy", + "pageSize", + "pageToken", + ) + ) + & set(("parent",)) + ) -def test_get_pool_rest_flattened(): +def test_list_dvr_sessions_rest_flattened(): client = LivestreamServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -18789,14 +18739,16 @@ 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 = service.ListDvrSessionsResponse() # get arguments that satisfy an http rule for this method - sample_request = {"name": "projects/sample1/locations/sample2/pools/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) @@ -18804,25 +18756,26 @@ def test_get_pool_rest_flattened(): response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = resources.Pool.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"} - client.get_pool(**mock_args) + 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/{name=projects/*/locations/*/pools/*}" % client.transport._host, + "%s/v1/{parent=projects/*/locations/*/channels/*}/dvrSessions" + % client.transport._host, args[1], ) -def test_get_pool_rest_flattened_error(transport: str = "rest"): +def test_list_dvr_sessions_rest_flattened_error(transport: str = "rest"): client = LivestreamServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -18831,56 +18784,118 @@ 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(), - 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", + client.list_dvr_sessions( + service.ListDvrSessionsRequest(), + 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.update_pool in client._transport._wrapped_methods +def test_list_dvr_sessions_rest_pager(transport: str = "rest"): + client = LivestreamServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. + # 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(), + ], + ), ) - client._transport._wrapped_methods[client._transport.update_pool] = mock_rpc + # Two responses for two calls + response = response + response - request = {} - client.update_pool(request) + # 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 - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 + sample_request = { + "parent": "projects/sample1/locations/sample2/channels/sample3" + } - # Operation methods build a cached wrapper on first rpc call - # subsequent calls should use the cached wrapper + 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", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 wrapper_fn.reset_mock() - client.update_pool(request) + # 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 + + 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_update_pool_rest_required_fields(request_type=service.UpdatePoolRequest): +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( @@ -18891,24 +18906,21 @@ 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) + ).get_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() - ).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", - ) - ) + ).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(), @@ -18917,7 +18929,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 = 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 @@ -18929,45 +18941,39 @@ 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 = 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.update_pool(request) + 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_update_pool_rest_unset_required_fields(): +def test_get_dvr_session_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",)) - ) + unset_fields = transport.get_dvr_session._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) -def test_update_pool_rest_flattened(): +def test_get_dvr_session_rest_flattened(): client = LivestreamServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -18976,41 +18982,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 = resources.DvrSession() # get arguments that satisfy an http rule for this method sample_request = { - "pool": {"name": "projects/sample1/locations/sample2/pools/sample3"} + "name": "projects/sample1/locations/sample2/channels/sample3/dvrSessions/sample4" } # 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"]), + 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.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.update_pool(**mock_args) + 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/{pool.name=projects/*/locations/*/pools/*}" % client.transport._host, + "%s/v1/{name=projects/*/locations/*/channels/*/dvrSessions/*}" + % client.transport._host, args[1], ) -def test_update_pool_rest_flattened_error(transport: str = "rest"): +def test_get_dvr_session_rest_flattened_error(transport: str = "rest"): client = LivestreamServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -19019,1651 +19027,3370 @@ 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.get_dvr_session( + service.GetDvrSessionRequest(), + name="name_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): +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=transport, + transport="rest", ) - # 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, - ) + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() - # It is an error to provide an api_key and a transport instance. - transport = transports.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, + # Ensure method has been cached + assert ( + client._transport.delete_dvr_session in client._transport._wrapped_methods ) - # It is an error to provide an api_key and a credential. - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = LivestreamServiceClient( - client_options=options, credentials=ga_credentials.AnonymousCredentials() + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. ) + client._transport._wrapped_methods[ + client._transport.delete_dvr_session + ] = mock_rpc - # 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, - ) + request = {} + client.delete_dvr_session(request) + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.LivestreamServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = LivestreamServiceClient(transport=transport) - assert client.transport is transport + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + client.delete_dvr_session(request) -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 + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 - transport = transports.LivestreamServiceGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel +def test_delete_dvr_session_rest_required_fields( + request_type=service.DeleteDvrSessionRequest, +): + transport_class = transports.LivestreamServiceRestTransport -@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() + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + # verify fields with default values are dropped -def test_transport_kind_grpc(): - transport = LivestreamServiceClient.get_transport_class("grpc")( + unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ) - assert transport.kind == "grpc" - + ).delete_dvr_session._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) -def test_initialize_client_w_grpc(): - client = LivestreamServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport="grpc" - ) - assert client is not None + # 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" -# This 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", + transport="rest", ) + request = request_type(**request_init) - # 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) + # 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.CreateChannelRequest() + 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_dvr_session(request) -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_list_channels_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.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() +def test_delete_dvr_session_rest_unset_required_fields(): + transport = transports.LivestreamServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) - assert args[0] == request_msg + unset_fields = transport.delete_dvr_session._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_get_channel_empty_call_grpc(): +def test_delete_dvr_session_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.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 + # Mock the http request call within the method and fake a response. + with mock.patch.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" + } -# This 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", - ) + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + ) + mock_args.update(sample_request) - # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.delete_channel), "__call__") as call: - call.return_value = operations_pb2.Operation(name="operations/op") - client.delete_channel(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.DeleteChannelRequest() + client.delete_dvr_session(**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/*/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. -def test_update_channel_empty_call_grpc(): +def test_delete_dvr_session_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.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() + # 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", + ) - assert args[0] == request_msg +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", + ) -# This 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", - ) + # 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.start_channel), "__call__") as call: - call.return_value = operations_pb2.Operation(name="operations/op") - client.start_channel(request=None) + # Ensure method has been cached + assert ( + client._transport.update_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.StartChannelRequest() + # Replace cached wrapped function with mock + mock_rpc = 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 - assert args[0] == request_msg + request = {} + client.update_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_stop_channel_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.stop_channel), "__call__") as call: - call.return_value = operations_pb2.Operation(name="operations/op") - client.stop_channel(request=None) + client.update_dvr_session(request) - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = service.StopChannelRequest() + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 - assert args[0] == request_msg +def test_update_dvr_session_rest_required_fields( + request_type=service.UpdateDvrSessionRequest, +): + 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_create_input_empty_call_grpc(): - client = LivestreamServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", + request_init = {} + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) ) - # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.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() + # verify fields with default values are dropped - assert args[0] == request_msg + 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 -# This 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", + 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) - # 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 - + # verify required fields with non-default values are left alone -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_get_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.get_input), "__call__") as call: - call.return_value = resources.Input() - client.get_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": "patch", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = service.GetInputRequest() + 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.update_dvr_session(request) -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_delete_input_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.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() +def test_update_dvr_session_rest_unset_required_fields(): + transport = transports.LivestreamServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) - assert args[0] == request_msg + unset_fields = transport.update_dvr_session._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "requestId", + "updateMask", + ) + ) + & set( + ( + "updateMask", + "dvrSession", + ) + ) + ) -# This 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(): +def test_update_dvr_session_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.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 + # Mock the http request call within the method and fake a response. + with mock.patch.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" + } + } -# This 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", - ) + # 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) - # 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) + # 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.CreateEventRequest() + client.update_dvr_session(**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/{dvr_session.name=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. -def test_list_events_empty_call_grpc(): +def test_update_dvr_session_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_events), "__call__") as call: - call.return_value = service.ListEventsResponse() - client.list_events(request=None) + # 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"]), + ) - # 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 +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() -# This 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", - ) + # Ensure method has been cached + assert client._transport.create_asset in client._transport._wrapped_methods - # 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) + # Replace cached wrapped function with mock + mock_rpc = 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 - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = service.GetEventRequest() + request = {} + client.create_asset(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_delete_event_empty_call_grpc(): - client = LivestreamServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) + client.create_asset(request) - # 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 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.DeleteEventRequest() - - assert args[0] == request_msg +def test_create_asset_rest_required_fields(request_type=service.CreateAssetRequest): + 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_clips_empty_call_grpc(): - client = LivestreamServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", + 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) ) - # 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) + # verify fields with default values are dropped + assert "assetId" not in jsonified_request - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = service.ListClipsRequest() + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).create_asset._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 "assetId" in jsonified_request + assert jsonified_request["assetId"] == request_init["asset_id"] + jsonified_request["parent"] = "parent_value" + jsonified_request["assetId"] = "asset_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_clip_empty_call_grpc(): - client = LivestreamServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", + 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) - # 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 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" -# This 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", + transport="rest", ) + request = request_type(**request_init) - # 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) + # 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.CreateClipRequest() + 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_asset(request) -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_delete_clip_empty_call_grpc(): - client = LivestreamServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) + expected_params = [ + ( + "assetId", + "", + ), + ("$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.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() +def test_create_asset_rest_unset_required_fields(): + transport = transports.LivestreamServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) - assert args[0] == request_msg + unset_fields = transport.create_asset._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "assetId", + "requestId", + ) + ) + & set( + ( + "parent", + "asset", + "assetId", + ) + ) + ) -# This 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(): +def test_create_asset_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_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 + # Mock the http request call within the method and fake a response. + with mock.patch.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"} -# This 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", - ) + # 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) - # 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) + # 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.ListDvrSessionsRequest() + client.create_asset(**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/*}/assets" % 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_dvr_session_empty_call_grpc(): +def test_create_asset_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_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() + # 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", + ) - assert args[0] == request_msg +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", + ) -# This 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", - ) + # 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.delete_dvr_session), "__call__" - ) as call: - call.return_value = operations_pb2.Operation(name="operations/op") - client.delete_dvr_session(request=None) + # Ensure method has been cached + assert client._transport.delete_asset in client._transport._wrapped_methods - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = service.DeleteDvrSessionRequest() + # Replace cached wrapped function with mock + mock_rpc = 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 - assert args[0] == request_msg + request = {} + client.delete_asset(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_dvr_session_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_dvr_session), "__call__" - ) as call: - call.return_value = operations_pb2.Operation(name="operations/op") - client.update_dvr_session(request=None) + client.delete_asset(request) - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = service.UpdateDvrSessionRequest() + # 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_asset_rest_required_fields(request_type=service.DeleteAssetRequest): + 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_create_asset_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.create_asset), "__call__") as call: - call.return_value = operations_pb2.Operation(name="operations/op") - client.create_asset(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.CreateAssetRequest() + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).delete_asset._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() + ).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" -# This 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", + transport="rest", ) + request = request_type(**request_init) - # 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) + # 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.DeleteAssetRequest() + 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_asset(request) -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_get_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.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() +def test_delete_asset_rest_unset_required_fields(): + transport = transports.LivestreamServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) - assert args[0] == request_msg + unset_fields = transport.delete_asset._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_list_assets_empty_call_grpc(): +def test_delete_asset_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.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 + # Mock the http request call within the method and fake a response. + with mock.patch.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"} -# This 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", - ) + # 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_pool), "__call__") as call: - call.return_value = resources.Pool() - client.get_pool(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.GetPoolRequest() + client.delete_asset(**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/*/assets/*}" % client.transport._host, + args[1], + ) -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_update_pool_empty_call_grpc(): +def test_delete_asset_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.update_pool), "__call__") as call: - call.return_value = operations_pb2.Operation(name="operations/op") - client.update_pool(request=None) + # 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", + ) - # 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_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() -def test_transport_kind_grpc_asyncio(): - transport = LivestreamServiceAsyncClient.get_transport_class("grpc_asyncio")( - credentials=async_anonymous_credentials() - ) - assert transport.kind == "grpc_asyncio" - + # Ensure method has been cached + assert client._transport.get_asset in client._transport._wrapped_methods -def test_initialize_client_w_grpc_asyncio(): - client = LivestreamServiceAsyncClient( - credentials=async_anonymous_credentials(), transport="grpc_asyncio" - ) - assert client is not 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.get_asset] = mock_rpc + request = {} + client.get_asset(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_channel_empty_call_grpc_asyncio(): - client = LivestreamServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 - # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.create_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) + client.get_asset(request) - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = service.CreateChannelRequest() + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 - assert args[0] == request_msg +def test_get_asset_rest_required_fields(request_type=service.GetAssetRequest): + 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. -@pytest.mark.asyncio -async def test_list_channels_empty_call_grpc_asyncio(): - client = LivestreamServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) ) - # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.list_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) + # 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.ListChannelsRequest() + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get_asset._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_channel_empty_call_grpc_asyncio(): - client = LivestreamServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get_asset._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) - # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.get_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) + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = service.GetChannelRequest() + 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 = 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 -# This test is a coverage 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", - ) + # Convert return value to protobuf type + return_value = resources.Asset.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.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) + response_value._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.DeleteChannelRequest() + response = client.get_asset(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_update_channel_empty_call_grpc_asyncio(): - client = LivestreamServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", +def test_get_asset_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.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) + unset_fields = transport.get_asset._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = service.UpdateChannelRequest() - assert args[0] == request_msg +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() -# This test is a coverage 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", - ) + # get arguments that satisfy an http rule for this method + sample_request = {"name": "projects/sample1/locations/sample2/assets/sample3"} - # 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") + # get truthy value for each flattened field + mock_args = dict( + name="name_value", ) - await client.start_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.StartChannelRequest() + # 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"} - assert args[0] == request_msg + 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], + ) -# This test is a coverage 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", +def test_get_asset_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.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") + # 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", ) - 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 +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() -# This test is a coverage 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", - ) + # Ensure method has been cached + assert client._transport.list_assets in client._transport._wrapped_methods - # 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") + # Replace cached 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.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 + client._transport._wrapped_methods[client._transport.list_assets] = mock_rpc + request = {} + client.list_assets(request) -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -@pytest.mark.asyncio -async def test_list_inputs_empty_call_grpc_asyncio(): - client = LivestreamServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 - # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.list_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) + client.list_assets(request) - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = service.ListInputsRequest() + # 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_list_assets_rest_required_fields(request_type=service.ListAssetsRequest): + 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. -@pytest.mark.asyncio -async def test_get_input_empty_call_grpc_asyncio(): - client = LivestreamServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) ) - # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.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) + # 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.GetInputRequest() + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).list_assets._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_delete_input_empty_call_grpc_asyncio(): - client = LivestreamServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", + 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) - # 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) + # 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.DeleteInputRequest() + 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.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 -# This test is a coverage 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", - ) + # Convert return value to protobuf type + return_value = service.ListAssetsResponse.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.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) + response_value._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.UpdateInputRequest() + response = client.list_assets(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_create_event_empty_call_grpc_asyncio(): - client = LivestreamServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", +def test_list_assets_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.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, + unset_fields = transport.list_assets._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "filter", + "orderBy", + "pageSize", + "pageToken", ) ) - 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() + & set(("parent",)) + ) - assert args[0] == request_msg +def test_list_assets_rest_flattened(): + 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. -@pytest.mark.asyncio -async def test_list_events_empty_call_grpc_asyncio(): - client = LivestreamServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) + # Mock the http request call within the method and 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() - # 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"], - ) + # 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", ) - await client.list_events(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.ListEventsRequest() + # 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"} - assert args[0] == request_msg + 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], + ) -# This test is a coverage 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", +def test_list_assets_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.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, - ) + # 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", ) - 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", +def test_list_assets_rest_pager(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.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) + # 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 - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = service.DeleteEventRequest() + # 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 - assert args[0] == request_msg + sample_request = {"parent": "projects/sample1/locations/sample2"} + pager = client.list_assets(request=sample_request) -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -@pytest.mark.asyncio -async def test_list_clips_empty_call_grpc_asyncio(): - client = LivestreamServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, resources.Asset) for i in results) - # 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) + 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 - # 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 +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() -# This test is a coverage 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", - ) + # Ensure method has been cached + assert client._transport.get_pool in client._transport._wrapped_methods - # 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, - ) + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. ) - await client.get_clip(request=None) + client._transport._wrapped_methods[client._transport.get_pool] = mock_rpc - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = service.GetClipRequest() + request = {} + client.get_pool(request) - assert args[0] == request_msg + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + client.get_pool(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", - ) + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 - # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.create_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() +def test_get_pool_rest_required_fields(request_type=service.GetPoolRequest): + transport_class = transports.LivestreamServiceRestTransport - assert args[0] == request_msg + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + # verify fields with default values are dropped -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -@pytest.mark.asyncio -async def test_delete_clip_empty_call_grpc_asyncio(): - client = LivestreamServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get_pool._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.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) + # 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.DeleteClipRequest() + jsonified_request["name"] = "name_value" - assert args[0] == request_msg + 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" -# This test is a coverage 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", + 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.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) + # 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 - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = service.CreateDvrSessionRequest() + response_value = Response() + response_value.status_code = 200 - assert args[0] == request_msg + # 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"} -# This test is a coverage 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", - ) + response = client.get_pool(request) - # 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) + 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.ListDvrSessionsRequest() - assert args[0] == request_msg +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",))) -# This test is a coverage 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", + +def test_get_pool_rest_flattened(): + 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: - # 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, - ) + # Mock the http request call within the method and 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", ) - await client.get_dvr_session(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.GetDvrSessionRequest() + # 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"} - assert args[0] == request_msg + 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], + ) -# This test is a coverage 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", + +def test_get_pool_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.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") + # 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", ) - 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 +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() -# This test is a coverage 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", - ) + # Ensure method has been cached + assert client._transport.update_pool in client._transport._wrapped_methods - # 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") + # Replace cached 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.update_dvr_session(request=None) + client._transport._wrapped_methods[client._transport.update_pool] = mock_rpc - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = service.UpdateDvrSessionRequest() + request = {} + client.update_pool(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. -@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) + client.update_pool(request) - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = service.CreateAssetRequest() + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 - assert args[0] == request_msg +def test_update_pool_rest_required_fields(request_type=service.UpdatePoolRequest): + 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. -@pytest.mark.asyncio -async def test_delete_asset_empty_call_grpc_asyncio(): - client = LivestreamServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", + request_init = {} + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) ) - # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.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 + # 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) -# This test is a coverage 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", - ) + # verify required fields with default values are now present - # 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, - ) + 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", ) - await client.get_asset(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.GetAssetRequest() + # verify required fields with non-default values are left alone - 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": "patch", + "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_assets_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_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) + response_value._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.ListAssetsRequest() + response = client.update_pool(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_pool_empty_call_grpc_asyncio(): - client = LivestreamServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", +def test_update_pool_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_pool), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - resources.Pool( - name="name_value", + unset_fields = transport.update_pool._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "requestId", + "updateMask", ) ) - await client.get_pool(request=None) + & set(("pool",)) + ) - # 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 +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") -# This test is a coverage 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", - ) + # get arguments that satisfy an http rule for this method + sample_request = { + "pool": {"name": "projects/sample1/locations/sample2/pools/sample3"} + } - # 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") + # 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"]), ) - 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.UpdatePoolRequest() + mock_args.update(sample_request) - assert args[0] == request_msg + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = 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) -def test_transport_kind_rest(): - transport = LivestreamServiceClient.get_transport_class("rest")( - credentials=ga_credentials.AnonymousCredentials() - ) - assert transport.kind == "rest" + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1/{pool.name=projects/*/locations/*/pools/*}" % client.transport._host, + args[1], + ) -def test_create_channel_rest_bad_request(request_type=service.CreateChannelRequest): +def test_update_pool_rest_flattened_error(transport: str = "rest"): client = LivestreamServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, ) - # 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) - + + # 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_start_distribution_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_distribution), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.start_distribution(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.StartDistributionRequest() + + assert args[0] == request_msg + + +# This 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_distribution_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_distribution), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.stop_distribution(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.StopDistributionRequest() + + assert args[0] == request_msg + + +# This 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_preview_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.preview_input), "__call__") as call: + call.return_value = service.PreviewInputResponse() + client.preview_input(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.PreviewInputRequest() + + assert args[0] == request_msg + + +# This 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_start_distribution_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_distribution), "__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_distribution(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.StartDistributionRequest() + + assert args[0] == request_msg + + +# This test is a coverage 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_distribution_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_distribution), "__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_distribution(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.StopDistributionRequest() + + assert args[0] == request_msg + + +# This test is a coverage 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_preview_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.preview_input), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + service.PreviewInputResponse( + uri="uri_value", + bearer_token="bearer_token_value", + ) + ) + await client.preview_input(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.PreviewInputRequest() + + assert args[0] == request_msg + + +# This test is a coverage 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.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", @@ -20715,7 +22442,20 @@ def test_create_channel_rest_call_success(request_type): "aq_strength": 0.1184, "profile": "profile_value", "tune": "tune_value", - } + }, + "h265": { + "width_pixels": 1300, + "height_pixels": 1389, + "frame_rate": 0.1046, + "bitrate_bps": 1167, + "gop_frame_count": 1592, + "gop_duration": {}, + "vbv_size_bits": 1401, + "vbv_fullness_bits": 1834, + "b_pyramid": True, + "b_frame_count": 1364, + "aq_strength": 0.1184, + }, }, "audio_stream": { "transmux": True, @@ -20737,7 +22477,20 @@ def test_create_channel_rest_call_success(request_type): ], "sample_rate_hertz": 1817, }, - "text_stream": {"codec": "codec_value"}, + "text_stream": { + "codec": "codec_value", + "language_code": "language_code_value", + "display_name": "display_name_value", + "output_cea_channel": "output_cea_channel_value", + "mapping_": [ + { + "input_key": "input_key_value", + "input_track": 1188, + "input_cea_channel": "input_cea_channel_value", + "from_language_code": "from_language_code_value", + } + ], + }, } ], "mux_streams": [ @@ -20763,29 +22516,52 @@ def test_create_channel_rest_call_success(request_type): "key": "key_value", } ], + "distribution_streams": [ + { + "key": "key_value", + "container": "container_value", + "elementary_streams": [ + "elementary_streams_value1", + "elementary_streams_value2", + ], + } + ], + "distributions": [ + { + "key": "key_value", + "distribution_stream": "distribution_stream_value", + "state": 5, + "error": { + "code": 411, + "message": "message_value", + "details": [ + { + "type_url": "type.googleapis.com/google.protobuf.Duration", + "value": b"\x08\x0c\x10\xdb\x07", + } + ], + }, + "srt_push": { + "uri": "uri_value", + "passphrase_secret_version": "passphrase_secret_version_value", + }, + "rtmp_push": {"uri": "uri_value", "stream_key": "stream_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", - } - ], - }, + "column_count": 1302, + "row_count": 992, + "interval": {}, + "quality": 777, + } + ], + "streaming_state": 1, + "streaming_error": {}, "log_config": {"log_severity": 1}, "timecode_config": { "source": 1, @@ -20817,6 +22593,7 @@ def test_create_channel_rest_call_success(request_type): "opacity": 0.761, } ], + "auto_transcription_config": {"display_timing": 1, "quality_preset": 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 @@ -20841,72 +22618,328 @@ def get_message_fields(field): 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) - ] + 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) + + # Mock the http request call within the method and fake a response. + with mock.patch.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) + + # 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): + 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_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 + + 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 + + client.create_channel( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +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 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) + + +@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" + ) + + # 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"], + ) + + # 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) + + # 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"] + + +@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) + + 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, + } + + req.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 + + 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"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + - subfields_not_in_runtime = [] +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) - # 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 + # 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) - 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] +@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" + ) + + # 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") + return_value = resources.Channel( + name="name_value", + active_input="active_input_value", + streaming_state=resources.Channel.StreamingState.STREAMING, + ) # 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.create_channel(request) + response = client.get_channel(request) # Establish that the response is the type that we expect. - json_return_value = json_format.MessageToJson(return_value) + 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 @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_create_channel_rest_interceptors(null_interceptor): +def test_get_channel_rest_interceptors(null_interceptor): transport = transports.LivestreamServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -20920,18 +22953,16 @@ def test_create_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_create_channel" + transports.LivestreamServiceRestInterceptor, "post_get_channel" ) as post, mock.patch.object( - transports.LivestreamServiceRestInterceptor, "post_create_channel_with_metadata" + transports.LivestreamServiceRestInterceptor, "post_get_channel_with_metadata" ) as post_with_metadata, mock.patch.object( - transports.LivestreamServiceRestInterceptor, "pre_create_channel" + transports.LivestreamServiceRestInterceptor, "pre_get_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.GetChannelRequest.pb(service.GetChannelRequest()) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -20942,19 +22973,19 @@ def test_create_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.Channel.to_json(resources.Channel()) req.return_value.content = return_value - request = service.CreateChannelRequest() + request = service.GetChannelRequest() 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.Channel() + post_with_metadata.return_value = resources.Channel(), metadata - client.create_channel( + client.get_channel( request, metadata=[ ("key", "val"), @@ -20967,12 +22998,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_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 = {"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. @@ -20987,53 +23018,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.delete_channel(request) @pytest.mark.parametrize( "request_type", [ - service.ListChannelsRequest, + service.DeleteChannelRequest, dict, ], ) -def test_list_channels_rest_call_success(request_type): +def test_delete_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.delete_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_delete_channel_rest_interceptors(null_interceptor): transport = transports.LivestreamServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -21047,16 +23070,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_delete_channel" ) as post, mock.patch.object( - transports.LivestreamServiceRestInterceptor, "post_list_channels_with_metadata" + transports.LivestreamServiceRestInterceptor, "post_delete_channel_with_metadata" ) as post_with_metadata, mock.patch.object( - transports.LivestreamServiceRestInterceptor, "pre_list_channels" + transports.LivestreamServiceRestInterceptor, "pre_delete_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.DeleteChannelRequest.pb(service.DeleteChannelRequest()) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -21067,102 +23092,350 @@ 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() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = service.ListChannelsResponse() - post_with_metadata.return_value = service.ListChannelsResponse(), metadata + 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"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +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 = { + "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. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.update_channel(request) + + +@pytest.mark.parametrize( + "request_type", + [ + service.UpdateChannelRequest, + dict, + ], +) +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 = { + "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", + }, + "h265": { + "width_pixels": 1300, + "height_pixels": 1389, + "frame_rate": 0.1046, + "bitrate_bps": 1167, + "gop_frame_count": 1592, + "gop_duration": {}, + "vbv_size_bits": 1401, + "vbv_fullness_bits": 1834, + "b_pyramid": True, + "b_frame_count": 1364, + "aq_strength": 0.1184, + }, + }, + "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", + "language_code": "language_code_value", + "display_name": "display_name_value", + "output_cea_channel": "output_cea_channel_value", + "mapping_": [ + { + "input_key": "input_key_value", + "input_track": 1188, + "input_cea_channel": "input_cea_channel_value", + "from_language_code": "from_language_code_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", + } + ], + "distribution_streams": [ + { + "key": "key_value", + "container": "container_value", + "elementary_streams": [ + "elementary_streams_value1", + "elementary_streams_value2", + ], + } + ], + "distributions": [ + { + "key": "key_value", + "distribution_stream": "distribution_stream_value", + "state": 5, + "error": { + "code": 411, + "message": "message_value", + "details": [ + { + "type_url": "type.googleapis.com/google.protobuf.Duration", + "value": b"\x08\x0c\x10\xdb\x07", + } + ], + }, + "srt_push": { + "uri": "uri_value", + "passphrase_secret_version": "passphrase_secret_version_value", + }, + "rtmp_push": {"uri": "uri_value", "stream_key": "stream_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": {}, + "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, + } + ], + "auto_transcription_config": {"display_timing": 1, "quality_preset": 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.UpdateChannelRequest.meta.fields["channel"] - client.list_channels( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] - pre.assert_called_once() - post.assert_called_once() - post_with_metadata.assert_called_once() + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields -def test_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) + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, "request") as req, pytest.raises( - core_exceptions.BadRequest - ): - # Wrap the value into a proper Response obj - response_value = mock.Mock() - json_return_value = "" - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = mock.Mock() - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.get_channel(request) + subfields_not_in_runtime = [] + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["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 -@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" - ) + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + { + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + } + ) - # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/locations/sample2/channels/sample3"} + # 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) # Mock the http request call within the method and 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.update_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 + 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_update_channel_rest_interceptors(null_interceptor): transport = transports.LivestreamServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -21176,16 +23449,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_update_channel" ) as post, mock.patch.object( - transports.LivestreamServiceRestInterceptor, "post_get_channel_with_metadata" + transports.LivestreamServiceRestInterceptor, "post_update_channel_with_metadata" ) as post_with_metadata, mock.patch.object( - transports.LivestreamServiceRestInterceptor, "pre_get_channel" + transports.LivestreamServiceRestInterceptor, "pre_update_channel" ) 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.UpdateChannelRequest.pb(service.UpdateChannelRequest()) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -21196,19 +23471,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.UpdateChannelRequest() 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.update_channel( request, metadata=[ ("key", "val"), @@ -21221,7 +23496,7 @@ 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_start_channel_rest_bad_request(request_type=service.StartChannelRequest): client = LivestreamServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) @@ -21241,17 +23516,17 @@ 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.start_channel(request) @pytest.mark.parametrize( "request_type", [ - service.DeleteChannelRequest, + service.StartChannelRequest, dict, ], ) -def test_delete_channel_rest_call_success(request_type): +def test_start_channel_rest_call_success(request_type): client = LivestreamServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) @@ -21272,14 +23547,14 @@ def test_delete_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.delete_channel(request) + 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_delete_channel_rest_interceptors(null_interceptor): +def test_start_channel_rest_interceptors(null_interceptor): transport = transports.LivestreamServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -21295,16 +23570,16 @@ def test_delete_channel_rest_interceptors(null_interceptor): ) as transcode, mock.patch.object( operation.Operation, "_set_result_from_operation" ), mock.patch.object( - transports.LivestreamServiceRestInterceptor, "post_delete_channel" + transports.LivestreamServiceRestInterceptor, "post_start_channel" ) as post, mock.patch.object( - transports.LivestreamServiceRestInterceptor, "post_delete_channel_with_metadata" + transports.LivestreamServiceRestInterceptor, "post_start_channel_with_metadata" ) as post_with_metadata, mock.patch.object( - transports.LivestreamServiceRestInterceptor, "pre_delete_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.DeleteChannelRequest.pb(service.DeleteChannelRequest()) + pb_message = service.StartChannelRequest.pb(service.StartChannelRequest()) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -21318,7 +23593,7 @@ def test_delete_channel_rest_interceptors(null_interceptor): return_value = json_format.MessageToJson(operations_pb2.Operation()) req.return_value.content = return_value - request = service.DeleteChannelRequest() + request = service.StartChannelRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), @@ -21327,7 +23602,7 @@ def test_delete_channel_rest_interceptors(null_interceptor): post.return_value = operations_pb2.Operation() post_with_metadata.return_value = operations_pb2.Operation(), metadata - client.delete_channel( + client.start_channel( request, metadata=[ ("key", "val"), @@ -21340,14 +23615,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_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 = { - "channel": {"name": "projects/sample1/locations/sample2/channels/sample3"} - } + 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. @@ -21355,238 +23628,30 @@ def test_update_channel_rest_bad_request(request_type=service.UpdateChannelReque core_exceptions.BadRequest ): # Wrap the value into a proper Response obj - response_value = mock.Mock() - json_return_value = "" - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = mock.Mock() - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.update_channel(request) - - -@pytest.mark.parametrize( - "request_type", - [ - service.UpdateChannelRequest, - dict, - ], -) -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 = { - "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 + 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.stop_channel(request) - if result and hasattr(result, "keys"): - for subfield in result.keys(): - if (field, subfield) not in runtime_nested_fields: - subfields_not_in_runtime.append( - { - "field": field, - "subfield": subfield, - "is_repeated": is_repeated, - } - ) - # Remove fields from the sample request which are not present in the runtime version of the dependency - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER - field = subfield_to_delete.get("field") - field_repeated = subfield_to_delete.get("is_repeated") - subfield = subfield_to_delete.get("subfield") - if subfield: - if field_repeated: - for i in range(0, len(request_init["channel"][field])): - del request_init["channel"][field][i][subfield] - else: - del request_init["channel"][field][subfield] +@pytest.mark.parametrize( + "request_type", + [ + service.StopChannelRequest, + dict, + ], +) +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 = {"name": "projects/sample1/locations/sample2/channels/sample3"} request = request_type(**request_init) # Mock the http request call within the method and fake a response. @@ -21601,14 +23666,14 @@ def get_message_fields(field): response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.update_channel(request) + response = client.stop_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_update_channel_rest_interceptors(null_interceptor): +def test_stop_channel_rest_interceptors(null_interceptor): transport = transports.LivestreamServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -21624,16 +23689,16 @@ def test_update_channel_rest_interceptors(null_interceptor): ) as transcode, mock.patch.object( operation.Operation, "_set_result_from_operation" ), mock.patch.object( - transports.LivestreamServiceRestInterceptor, "post_update_channel" + transports.LivestreamServiceRestInterceptor, "post_stop_channel" ) as post, mock.patch.object( - transports.LivestreamServiceRestInterceptor, "post_update_channel_with_metadata" + transports.LivestreamServiceRestInterceptor, "post_stop_channel_with_metadata" ) as post_with_metadata, mock.patch.object( - transports.LivestreamServiceRestInterceptor, "pre_update_channel" + transports.LivestreamServiceRestInterceptor, "pre_stop_channel" ) 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.StopChannelRequest.pb(service.StopChannelRequest()) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -21647,7 +23712,7 @@ def test_update_channel_rest_interceptors(null_interceptor): return_value = json_format.MessageToJson(operations_pb2.Operation()) req.return_value.content = return_value - request = service.UpdateChannelRequest() + request = service.StopChannelRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), @@ -21656,7 +23721,7 @@ def test_update_channel_rest_interceptors(null_interceptor): post.return_value = operations_pb2.Operation() post_with_metadata.return_value = operations_pb2.Operation(), metadata - client.update_channel( + client.stop_channel( request, metadata=[ ("key", "val"), @@ -21669,7 +23734,9 @@ 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_start_distribution_rest_bad_request( + request_type=service.StartDistributionRequest, +): client = LivestreamServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) @@ -21689,17 +23756,17 @@ 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.start_distribution(request) @pytest.mark.parametrize( "request_type", [ - service.StartChannelRequest, + service.StartDistributionRequest, dict, ], ) -def test_start_channel_rest_call_success(request_type): +def test_start_distribution_rest_call_success(request_type): client = LivestreamServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) @@ -21720,14 +23787,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.start_distribution(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_start_distribution_rest_interceptors(null_interceptor): transport = transports.LivestreamServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -21743,16 +23810,19 @@ 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_start_distribution" ) as post, mock.patch.object( - transports.LivestreamServiceRestInterceptor, "post_start_channel_with_metadata" + transports.LivestreamServiceRestInterceptor, + "post_start_distribution_with_metadata", ) as post_with_metadata, mock.patch.object( - transports.LivestreamServiceRestInterceptor, "pre_start_channel" + transports.LivestreamServiceRestInterceptor, "pre_start_distribution" ) 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.StartDistributionRequest.pb( + service.StartDistributionRequest() + ) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -21766,7 +23836,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.StartDistributionRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), @@ -21775,7 +23845,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.start_distribution( request, metadata=[ ("key", "val"), @@ -21788,7 +23858,9 @@ 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_stop_distribution_rest_bad_request( + request_type=service.StopDistributionRequest, +): client = LivestreamServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) @@ -21808,17 +23880,17 @@ 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.stop_distribution(request) @pytest.mark.parametrize( "request_type", [ - service.StopChannelRequest, + service.StopDistributionRequest, dict, ], ) -def test_stop_channel_rest_call_success(request_type): +def test_stop_distribution_rest_call_success(request_type): client = LivestreamServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) @@ -21839,14 +23911,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.stop_distribution(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_stop_distribution_rest_interceptors(null_interceptor): transport = transports.LivestreamServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -21862,16 +23934,19 @@ 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_stop_distribution" ) as post, mock.patch.object( - transports.LivestreamServiceRestInterceptor, "post_stop_channel_with_metadata" + transports.LivestreamServiceRestInterceptor, + "post_stop_distribution_with_metadata", ) as post_with_metadata, mock.patch.object( - transports.LivestreamServiceRestInterceptor, "pre_stop_channel" + transports.LivestreamServiceRestInterceptor, "pre_stop_distribution" ) 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.StopDistributionRequest.pb( + service.StopDistributionRequest() + ) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -21885,7 +23960,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.StopDistributionRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), @@ -21894,7 +23969,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.stop_distribution( request, metadata=[ ("key", "val"), @@ -22760,6 +24835,133 @@ def test_update_input_rest_interceptors(null_interceptor): post_with_metadata.assert_called_once() +def test_preview_input_rest_bad_request(request_type=service.PreviewInputRequest): + 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 = 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.preview_input(request) + + +@pytest.mark.parametrize( + "request_type", + [ + service.PreviewInputRequest, + dict, + ], +) +def test_preview_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/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 = service.PreviewInputResponse( + uri="uri_value", + bearer_token="bearer_token_value", + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = service.PreviewInputResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.preview_input(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, service.PreviewInputResponse) + assert response.uri == "uri_value" + assert response.bearer_token == "bearer_token_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_preview_input_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_preview_input" + ) as post, mock.patch.object( + transports.LivestreamServiceRestInterceptor, "post_preview_input_with_metadata" + ) as post_with_metadata, mock.patch.object( + transports.LivestreamServiceRestInterceptor, "pre_preview_input" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = service.PreviewInputRequest.pb(service.PreviewInputRequest()) + 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 = service.PreviewInputResponse.to_json( + service.PreviewInputResponse() + ) + req.return_value.content = return_value + + request = service.PreviewInputRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = service.PreviewInputResponse() + post_with_metadata.return_value = service.PreviewInputResponse(), metadata + + client.preview_input( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + def test_create_event_rest_bad_request(request_type=service.CreateEventRequest): client = LivestreamServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" @@ -22808,6 +25010,16 @@ def test_create_event_rest_call_success(request_type): "slate": {"duration": {}, "asset": "asset_value"}, "mute": {"duration": {}}, "unmute": {}, + "update_encryptions": { + "encryptions": [ + { + "id": "id_value", + "secret_manager_key_source": { + "secret_version": "secret_version_value" + }, + } + ] + }, "execute_now": True, "execution_time": {}, "state": 1, @@ -26167,6 +28379,50 @@ def test_stop_channel_empty_call_rest(): assert args[0] == request_msg +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_start_distribution_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.start_distribution), "__call__" + ) as call: + client.start_distribution(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.StartDistributionRequest() + + assert args[0] == request_msg + + +# This 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_distribution_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.stop_distribution), "__call__" + ) as call: + client.stop_distribution(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.StopDistributionRequest() + + assert args[0] == request_msg + + # This 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_rest(): @@ -26267,6 +28523,26 @@ def test_update_input_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_preview_input_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.preview_input), "__call__") as call: + client.preview_input(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.PreviewInputRequest() + + assert args[0] == request_msg + + # This 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_rest(): @@ -26712,11 +28988,14 @@ def test_livestream_service_base_transport(): "update_channel", "start_channel", "stop_channel", + "start_distribution", + "stop_distribution", "create_input", "list_inputs", "get_input", "delete_input", "update_input", + "preview_input", "create_event", "list_events", "get_event", @@ -27026,6 +29305,12 @@ def test_livestream_service_client_transport_session_collision(transport_name): session1 = client1.transport.stop_channel._session session2 = client2.transport.stop_channel._session assert session1 != session2 + session1 = client1.transport.start_distribution._session + session2 = client2.transport.start_distribution._session + assert session1 != session2 + session1 = client1.transport.stop_distribution._session + session2 = client2.transport.stop_distribution._session + assert session1 != session2 session1 = client1.transport.create_input._session session2 = client2.transport.create_input._session assert session1 != session2 @@ -27041,6 +29326,9 @@ def test_livestream_service_client_transport_session_collision(transport_name): session1 = client1.transport.update_input._session session2 = client2.transport.update_input._session assert session1 != session2 + session1 = client1.transport.preview_input._session + session2 = client2.transport.preview_input._session + assert session1 != session2 session1 = client1.transport.create_event._session session2 = client2.transport.create_event._session assert session1 != session2