diff --git a/.github/.OwlBot.lock.yaml b/.github/.OwlBot.lock.yaml index f0f3b24b..33a473d5 100644 --- a/.github/.OwlBot.lock.yaml +++ b/.github/.OwlBot.lock.yaml @@ -13,4 +13,5 @@ # limitations under the License. docker: image: gcr.io/cloud-devrel-public-resources/owlbot-python:latest - digest: sha256:f946c75373c2b0040e8e318c5e85d0cf46bc6e61d0a01f3ef94d8de974ac6790 + digest: sha256:8555f0e37e6261408f792bfd6635102d2da5ad73f8f09bcb24f25e6afb5fac97 + diff --git a/.kokoro/requirements.in b/.kokoro/requirements.in index cbd7e77f..882178ce 100644 --- a/.kokoro/requirements.in +++ b/.kokoro/requirements.in @@ -1,5 +1,5 @@ gcp-docuploader -gcp-releasetool +gcp-releasetool>=1.10.5 # required for compatibility with cryptography>=39.x importlib-metadata typing-extensions twine diff --git a/.kokoro/requirements.txt b/.kokoro/requirements.txt index 05dc4672..fa99c129 100644 --- a/.kokoro/requirements.txt +++ b/.kokoro/requirements.txt @@ -113,33 +113,28 @@ commonmark==0.9.1 \ --hash=sha256:452f9dc859be7f06631ddcb328b6919c67984aca654e5fefb3914d54691aed60 \ --hash=sha256:da2f38c92590f83de410ba1a3cbceafbc74fee9def35f9251ba9a971d6d66fd9 # via rich -cryptography==38.0.3 \ - --hash=sha256:068147f32fa662c81aebab95c74679b401b12b57494872886eb5c1139250ec5d \ - --hash=sha256:06fc3cc7b6f6cca87bd56ec80a580c88f1da5306f505876a71c8cfa7050257dd \ - --hash=sha256:25c1d1f19729fb09d42e06b4bf9895212292cb27bb50229f5aa64d039ab29146 \ - --hash=sha256:402852a0aea73833d982cabb6d0c3bb582c15483d29fb7085ef2c42bfa7e38d7 \ - --hash=sha256:4e269dcd9b102c5a3d72be3c45d8ce20377b8076a43cbed6f660a1afe365e436 \ - --hash=sha256:5419a127426084933076132d317911e3c6eb77568a1ce23c3ac1e12d111e61e0 \ - --hash=sha256:554bec92ee7d1e9d10ded2f7e92a5d70c1f74ba9524947c0ba0c850c7b011828 \ - --hash=sha256:5e89468fbd2fcd733b5899333bc54d0d06c80e04cd23d8c6f3e0542358c6060b \ - --hash=sha256:65535bc550b70bd6271984d9863a37741352b4aad6fb1b3344a54e6950249b55 \ - --hash=sha256:6ab9516b85bebe7aa83f309bacc5f44a61eeb90d0b4ec125d2d003ce41932d36 \ - --hash=sha256:6addc3b6d593cd980989261dc1cce38263c76954d758c3c94de51f1e010c9a50 \ - --hash=sha256:728f2694fa743a996d7784a6194da430f197d5c58e2f4e278612b359f455e4a2 \ - --hash=sha256:785e4056b5a8b28f05a533fab69febf5004458e20dad7e2e13a3120d8ecec75a \ - --hash=sha256:78cf5eefac2b52c10398a42765bfa981ce2372cbc0457e6bf9658f41ec3c41d8 \ - --hash=sha256:7f836217000342d448e1c9a342e9163149e45d5b5eca76a30e84503a5a96cab0 \ - --hash=sha256:8d41a46251bf0634e21fac50ffd643216ccecfaf3701a063257fe0b2be1b6548 \ - --hash=sha256:984fe150f350a3c91e84de405fe49e688aa6092b3525f407a18b9646f6612320 \ - --hash=sha256:9b24bcff7853ed18a63cfb0c2b008936a9554af24af2fb146e16d8e1aed75748 \ - --hash=sha256:b1b35d9d3a65542ed2e9d90115dfd16bbc027b3f07ee3304fc83580f26e43249 \ - --hash=sha256:b1b52c9e5f8aa2b802d48bd693190341fae201ea51c7a167d69fc48b60e8a959 \ - --hash=sha256:bbf203f1a814007ce24bd4d51362991d5cb90ba0c177a9c08825f2cc304d871f \ - --hash=sha256:be243c7e2bfcf6cc4cb350c0d5cdf15ca6383bbcb2a8ef51d3c9411a9d4386f0 \ - --hash=sha256:bfbe6ee19615b07a98b1d2287d6a6073f734735b49ee45b11324d85efc4d5cbd \ - --hash=sha256:c46837ea467ed1efea562bbeb543994c2d1f6e800785bd5a2c98bc096f5cb220 \ - --hash=sha256:dfb4f4dd568de1b6af9f4cda334adf7d72cf5bc052516e1b2608b683375dd95c \ - --hash=sha256:ed7b00096790213e09eb11c97cc6e2b757f15f3d2f85833cd2d3ec3fe37c1722 +cryptography==39.0.1 \ + --hash=sha256:0f8da300b5c8af9f98111ffd512910bc792b4c77392a9523624680f7956a99d4 \ + --hash=sha256:35f7c7d015d474f4011e859e93e789c87d21f6f4880ebdc29896a60403328f1f \ + --hash=sha256:5aa67414fcdfa22cf052e640cb5ddc461924a045cacf325cd164e65312d99502 \ + --hash=sha256:5d2d8b87a490bfcd407ed9d49093793d0f75198a35e6eb1a923ce1ee86c62b41 \ + --hash=sha256:6687ef6d0a6497e2b58e7c5b852b53f62142cfa7cd1555795758934da363a965 \ + --hash=sha256:6f8ba7f0328b79f08bdacc3e4e66fb4d7aab0c3584e0bd41328dce5262e26b2e \ + --hash=sha256:706843b48f9a3f9b9911979761c91541e3d90db1ca905fd63fee540a217698bc \ + --hash=sha256:807ce09d4434881ca3a7594733669bd834f5b2c6d5c7e36f8c00f691887042ad \ + --hash=sha256:83e17b26de248c33f3acffb922748151d71827d6021d98c70e6c1a25ddd78505 \ + --hash=sha256:96f1157a7c08b5b189b16b47bc9db2332269d6680a196341bf30046330d15388 \ + --hash=sha256:aec5a6c9864be7df2240c382740fcf3b96928c46604eaa7f3091f58b878c0bb6 \ + --hash=sha256:b0afd054cd42f3d213bf82c629efb1ee5f22eba35bf0eec88ea9ea7304f511a2 \ + --hash=sha256:ced4e447ae29ca194449a3f1ce132ded8fcab06971ef5f618605aacaa612beac \ + --hash=sha256:d1f6198ee6d9148405e49887803907fe8962a23e6c6f83ea7d98f1c0de375695 \ + --hash=sha256:e124352fd3db36a9d4a21c1aa27fd5d051e621845cb87fb851c08f4f75ce8be6 \ + --hash=sha256:e422abdec8b5fa8462aa016786680720d78bdce7a30c652b7fadf83a4ba35336 \ + --hash=sha256:ef8b72fa70b348724ff1218267e7f7375b8de4e8194d1636ee60510aae104cd0 \ + --hash=sha256:f0c64d1bd842ca2633e74a1a28033d139368ad959872533b1bab8c80e8240a0c \ + --hash=sha256:f24077a3b5298a5a06a8e0536e3ea9ec60e4c7ac486755e5fb6e6ea9b3500106 \ + --hash=sha256:fdd188c8a6ef8769f148f88f859884507b954cc64db6b52f66ef199bb9ad660a \ + --hash=sha256:fe913f20024eb2cb2f323e42a64bdf2911bb9738a15dba7d3cce48151034e3a8 # via # gcp-releasetool # secretstorage @@ -159,9 +154,9 @@ gcp-docuploader==0.6.4 \ --hash=sha256:01486419e24633af78fd0167db74a2763974765ee8078ca6eb6964d0ebd388af \ --hash=sha256:70861190c123d907b3b067da896265ead2eeb9263969d6955c9e0bb091b5ccbf # via -r requirements.in -gcp-releasetool==1.10.0 \ - --hash=sha256:72a38ca91b59c24f7e699e9227c90cbe4dd71b789383cb0164b088abae294c83 \ - --hash=sha256:8c7c99320208383d4bb2b808c6880eb7a81424afe7cdba3c8d84b25f4f0e097d +gcp-releasetool==1.10.5 \ + --hash=sha256:174b7b102d704b254f2a26a3eda2c684fd3543320ec239baf771542a2e58e109 \ + --hash=sha256:e29d29927fe2ca493105a82958c6873bb2b90d503acac56be2c229e74de0eec9 # via -r requirements.in google-api-core==2.10.2 \ --hash=sha256:10c06f7739fe57781f87523375e8e1a3a4674bf6392cd6131a3222182b971320 \ diff --git a/.release-please-manifest.json b/.release-please-manifest.json index fb1c7659..f2565cce 100644 --- a/.release-please-manifest.json +++ b/.release-please-manifest.json @@ -1,4 +1,4 @@ { - ".": "2.17.3" + ".": "2.18.0" } \ No newline at end of file diff --git a/CHANGELOG.md b/CHANGELOG.md index c9c3cab0..ea0269c1 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,14 @@ [1]: https://pypi.org/project/google-cloud-speech/#history +## [2.18.0](https://github.com/googleapis/python-speech/compare/v2.17.3...v2.18.0) (2023-02-28) + + +### Features + +* Enable "rest" transport in Python for services supporting numeric enums ([a20d0f1](https://github.com/googleapis/python-speech/commit/a20d0f15a81e0ad9190f48cb4bc21b3580b7e1f0)) +* Voice Activity Detection - adding speech event time and speech event type ([a20d0f1](https://github.com/googleapis/python-speech/commit/a20d0f15a81e0ad9190f48cb4bc21b3580b7e1f0)) + ## [2.17.3](https://github.com/googleapis/python-speech/compare/v2.17.2...v2.17.3) (2023-02-02) diff --git a/google/cloud/speech/gapic_version.py b/google/cloud/speech/gapic_version.py index 36f3d159..f09943f6 100644 --- a/google/cloud/speech/gapic_version.py +++ b/google/cloud/speech/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "2.17.3" # {x-release-please-version} +__version__ = "2.18.0" # {x-release-please-version} diff --git a/google/cloud/speech_v1/gapic_metadata.json b/google/cloud/speech_v1/gapic_metadata.json index aee75af1..b2de8253 100644 --- a/google/cloud/speech_v1/gapic_metadata.json +++ b/google/cloud/speech_v1/gapic_metadata.json @@ -116,6 +116,61 @@ ] } } + }, + "rest": { + "libraryClient": "AdaptationClient", + "rpcs": { + "CreateCustomClass": { + "methods": [ + "create_custom_class" + ] + }, + "CreatePhraseSet": { + "methods": [ + "create_phrase_set" + ] + }, + "DeleteCustomClass": { + "methods": [ + "delete_custom_class" + ] + }, + "DeletePhraseSet": { + "methods": [ + "delete_phrase_set" + ] + }, + "GetCustomClass": { + "methods": [ + "get_custom_class" + ] + }, + "GetPhraseSet": { + "methods": [ + "get_phrase_set" + ] + }, + "ListCustomClasses": { + "methods": [ + "list_custom_classes" + ] + }, + "ListPhraseSet": { + "methods": [ + "list_phrase_set" + ] + }, + "UpdateCustomClass": { + "methods": [ + "update_custom_class" + ] + }, + "UpdatePhraseSet": { + "methods": [ + "update_phrase_set" + ] + } + } } } }, @@ -160,6 +215,26 @@ ] } } + }, + "rest": { + "libraryClient": "SpeechClient", + "rpcs": { + "LongRunningRecognize": { + "methods": [ + "long_running_recognize" + ] + }, + "Recognize": { + "methods": [ + "recognize" + ] + }, + "StreamingRecognize": { + "methods": [ + "streaming_recognize" + ] + } + } } } } diff --git a/google/cloud/speech_v1/gapic_version.py b/google/cloud/speech_v1/gapic_version.py index 36f3d159..f09943f6 100644 --- a/google/cloud/speech_v1/gapic_version.py +++ b/google/cloud/speech_v1/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "2.17.3" # {x-release-please-version} +__version__ = "2.18.0" # {x-release-please-version} diff --git a/google/cloud/speech_v1/services/adaptation/client.py b/google/cloud/speech_v1/services/adaptation/client.py index 4a830bf2..d79aadb4 100644 --- a/google/cloud/speech_v1/services/adaptation/client.py +++ b/google/cloud/speech_v1/services/adaptation/client.py @@ -54,6 +54,7 @@ from .transports.base import AdaptationTransport, DEFAULT_CLIENT_INFO from .transports.grpc import AdaptationGrpcTransport from .transports.grpc_asyncio import AdaptationGrpcAsyncIOTransport +from .transports.rest import AdaptationRestTransport class AdaptationClientMeta(type): @@ -67,6 +68,7 @@ class AdaptationClientMeta(type): _transport_registry = OrderedDict() # type: Dict[str, Type[AdaptationTransport]] _transport_registry["grpc"] = AdaptationGrpcTransport _transport_registry["grpc_asyncio"] = AdaptationGrpcAsyncIOTransport + _transport_registry["rest"] = AdaptationRestTransport def get_transport_class( cls, diff --git a/google/cloud/speech_v1/services/adaptation/transports/__init__.py b/google/cloud/speech_v1/services/adaptation/transports/__init__.py index 1a966428..8a945154 100644 --- a/google/cloud/speech_v1/services/adaptation/transports/__init__.py +++ b/google/cloud/speech_v1/services/adaptation/transports/__init__.py @@ -19,15 +19,20 @@ from .base import AdaptationTransport from .grpc import AdaptationGrpcTransport from .grpc_asyncio import AdaptationGrpcAsyncIOTransport +from .rest import AdaptationRestTransport +from .rest import AdaptationRestInterceptor # Compile a registry of transports. _transport_registry = OrderedDict() # type: Dict[str, Type[AdaptationTransport]] _transport_registry["grpc"] = AdaptationGrpcTransport _transport_registry["grpc_asyncio"] = AdaptationGrpcAsyncIOTransport +_transport_registry["rest"] = AdaptationRestTransport __all__ = ( "AdaptationTransport", "AdaptationGrpcTransport", "AdaptationGrpcAsyncIOTransport", + "AdaptationRestTransport", + "AdaptationRestInterceptor", ) diff --git a/google/cloud/speech_v1/services/adaptation/transports/rest.py b/google/cloud/speech_v1/services/adaptation/transports/rest.py new file mode 100644 index 00000000..c7139ebd --- /dev/null +++ b/google/cloud/speech_v1/services/adaptation/transports/rest.py @@ -0,0 +1,1691 @@ +# -*- coding: utf-8 -*- +# 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. +# + +from google.auth.transport.requests import AuthorizedSession # type: ignore +import json # type: ignore +import grpc # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.api_core import exceptions as core_exceptions +from google.api_core import retry as retries +from google.api_core import rest_helpers +from google.api_core import rest_streaming +from google.api_core import path_template +from google.api_core import gapic_v1 + +from google.protobuf import json_format +from google.longrunning import operations_pb2 +from requests import __version__ as requests_version +import dataclasses +import re +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union +import warnings + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + + +from google.cloud.speech_v1.types import cloud_speech_adaptation +from google.cloud.speech_v1.types import resource +from google.protobuf import empty_pb2 # type: ignore + +from .base import AdaptationTransport, DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, + grpc_version=None, + rest_version=requests_version, +) + + +class AdaptationRestInterceptor: + """Interceptor for Adaptation. + + Interceptors are used to manipulate requests, request metadata, and responses + in arbitrary ways. + Example use cases include: + * Logging + * Verifying requests according to service or custom semantics + * Stripping extraneous information from responses + + These use cases and more can be enabled by injecting an + instance of a custom subclass when constructing the AdaptationRestTransport. + + .. code-block:: python + class MyCustomAdaptationInterceptor(AdaptationRestInterceptor): + def pre_create_custom_class(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_custom_class(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_create_phrase_set(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_phrase_set(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_delete_custom_class(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def pre_delete_phrase_set(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def pre_get_custom_class(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_custom_class(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_phrase_set(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_phrase_set(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_custom_classes(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_custom_classes(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_phrase_set(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_phrase_set(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_custom_class(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_custom_class(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_phrase_set(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_phrase_set(self, response): + logging.log(f"Received response: {response}") + return response + + transport = AdaptationRestTransport(interceptor=MyCustomAdaptationInterceptor()) + client = AdaptationClient(transport=transport) + + + """ + + def pre_create_custom_class( + self, + request: cloud_speech_adaptation.CreateCustomClassRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[ + cloud_speech_adaptation.CreateCustomClassRequest, Sequence[Tuple[str, str]] + ]: + """Pre-rpc interceptor for create_custom_class + + Override in a subclass to manipulate the request or metadata + before they are sent to the Adaptation server. + """ + return request, metadata + + def post_create_custom_class( + self, response: resource.CustomClass + ) -> resource.CustomClass: + """Post-rpc interceptor for create_custom_class + + Override in a subclass to manipulate the response + after it is returned by the Adaptation server but before + it is returned to user code. + """ + return response + + def pre_create_phrase_set( + self, + request: cloud_speech_adaptation.CreatePhraseSetRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[ + cloud_speech_adaptation.CreatePhraseSetRequest, Sequence[Tuple[str, str]] + ]: + """Pre-rpc interceptor for create_phrase_set + + Override in a subclass to manipulate the request or metadata + before they are sent to the Adaptation server. + """ + return request, metadata + + def post_create_phrase_set( + self, response: resource.PhraseSet + ) -> resource.PhraseSet: + """Post-rpc interceptor for create_phrase_set + + Override in a subclass to manipulate the response + after it is returned by the Adaptation server but before + it is returned to user code. + """ + return response + + def pre_delete_custom_class( + self, + request: cloud_speech_adaptation.DeleteCustomClassRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[ + cloud_speech_adaptation.DeleteCustomClassRequest, Sequence[Tuple[str, str]] + ]: + """Pre-rpc interceptor for delete_custom_class + + Override in a subclass to manipulate the request or metadata + before they are sent to the Adaptation server. + """ + return request, metadata + + def pre_delete_phrase_set( + self, + request: cloud_speech_adaptation.DeletePhraseSetRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[ + cloud_speech_adaptation.DeletePhraseSetRequest, Sequence[Tuple[str, str]] + ]: + """Pre-rpc interceptor for delete_phrase_set + + Override in a subclass to manipulate the request or metadata + before they are sent to the Adaptation server. + """ + return request, metadata + + def pre_get_custom_class( + self, + request: cloud_speech_adaptation.GetCustomClassRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[ + cloud_speech_adaptation.GetCustomClassRequest, Sequence[Tuple[str, str]] + ]: + """Pre-rpc interceptor for get_custom_class + + Override in a subclass to manipulate the request or metadata + before they are sent to the Adaptation server. + """ + return request, metadata + + def post_get_custom_class( + self, response: resource.CustomClass + ) -> resource.CustomClass: + """Post-rpc interceptor for get_custom_class + + Override in a subclass to manipulate the response + after it is returned by the Adaptation server but before + it is returned to user code. + """ + return response + + def pre_get_phrase_set( + self, + request: cloud_speech_adaptation.GetPhraseSetRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[cloud_speech_adaptation.GetPhraseSetRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_phrase_set + + Override in a subclass to manipulate the request or metadata + before they are sent to the Adaptation server. + """ + return request, metadata + + def post_get_phrase_set(self, response: resource.PhraseSet) -> resource.PhraseSet: + """Post-rpc interceptor for get_phrase_set + + Override in a subclass to manipulate the response + after it is returned by the Adaptation server but before + it is returned to user code. + """ + return response + + def pre_list_custom_classes( + self, + request: cloud_speech_adaptation.ListCustomClassesRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[ + cloud_speech_adaptation.ListCustomClassesRequest, Sequence[Tuple[str, str]] + ]: + """Pre-rpc interceptor for list_custom_classes + + Override in a subclass to manipulate the request or metadata + before they are sent to the Adaptation server. + """ + return request, metadata + + def post_list_custom_classes( + self, response: cloud_speech_adaptation.ListCustomClassesResponse + ) -> cloud_speech_adaptation.ListCustomClassesResponse: + """Post-rpc interceptor for list_custom_classes + + Override in a subclass to manipulate the response + after it is returned by the Adaptation server but before + it is returned to user code. + """ + return response + + def pre_list_phrase_set( + self, + request: cloud_speech_adaptation.ListPhraseSetRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[cloud_speech_adaptation.ListPhraseSetRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_phrase_set + + Override in a subclass to manipulate the request or metadata + before they are sent to the Adaptation server. + """ + return request, metadata + + def post_list_phrase_set( + self, response: cloud_speech_adaptation.ListPhraseSetResponse + ) -> cloud_speech_adaptation.ListPhraseSetResponse: + """Post-rpc interceptor for list_phrase_set + + Override in a subclass to manipulate the response + after it is returned by the Adaptation server but before + it is returned to user code. + """ + return response + + def pre_update_custom_class( + self, + request: cloud_speech_adaptation.UpdateCustomClassRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[ + cloud_speech_adaptation.UpdateCustomClassRequest, Sequence[Tuple[str, str]] + ]: + """Pre-rpc interceptor for update_custom_class + + Override in a subclass to manipulate the request or metadata + before they are sent to the Adaptation server. + """ + return request, metadata + + def post_update_custom_class( + self, response: resource.CustomClass + ) -> resource.CustomClass: + """Post-rpc interceptor for update_custom_class + + Override in a subclass to manipulate the response + after it is returned by the Adaptation server but before + it is returned to user code. + """ + return response + + def pre_update_phrase_set( + self, + request: cloud_speech_adaptation.UpdatePhraseSetRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[ + cloud_speech_adaptation.UpdatePhraseSetRequest, Sequence[Tuple[str, str]] + ]: + """Pre-rpc interceptor for update_phrase_set + + Override in a subclass to manipulate the request or metadata + before they are sent to the Adaptation server. + """ + return request, metadata + + def post_update_phrase_set( + self, response: resource.PhraseSet + ) -> resource.PhraseSet: + """Post-rpc interceptor for update_phrase_set + + Override in a subclass to manipulate the response + after it is returned by the Adaptation server but before + it is returned to user code. + """ + return response + + def pre_get_operation( + self, + request: operations_pb2.GetOperationRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[operations_pb2.GetOperationRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_operation + + Override in a subclass to manipulate the request or metadata + before they are sent to the Adaptation server. + """ + return request, metadata + + def post_get_operation( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for get_operation + + Override in a subclass to manipulate the response + after it is returned by the Adaptation server but before + it is returned to user code. + """ + return response + + def pre_list_operations( + self, + request: operations_pb2.ListOperationsRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[operations_pb2.ListOperationsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_operations + + Override in a subclass to manipulate the request or metadata + before they are sent to the Adaptation server. + """ + return request, metadata + + def post_list_operations( + self, response: operations_pb2.ListOperationsResponse + ) -> operations_pb2.ListOperationsResponse: + """Post-rpc interceptor for list_operations + + Override in a subclass to manipulate the response + after it is returned by the Adaptation server but before + it is returned to user code. + """ + return response + + +@dataclasses.dataclass +class AdaptationRestStub: + _session: AuthorizedSession + _host: str + _interceptor: AdaptationRestInterceptor + + +class AdaptationRestTransport(AdaptationTransport): + """REST backend transport for Adaptation. + + Service that implements Google Cloud Speech Adaptation API. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends JSON representations of protocol buffers over HTTP/1.1 + + """ + + def __init__( + self, + *, + host: str = "speech.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + url_scheme: str = "https", + interceptor: Optional[AdaptationRestInterceptor] = None, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + client_cert_source_for_mtls (Callable[[], Tuple[bytes, bytes]]): Client + certificate to configure mutual TLS HTTP channel. It is ignored + if ``channel`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you are developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + url_scheme: the protocol scheme for the API endpoint. Normally + "https", but for testing or local servers, + "http" can be specified. + """ + # Run the base constructor + # TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc. + # TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the + # credentials object + maybe_url_match = re.match("^(?Phttp(?:s)?://)?(?P.*)$", host) + if maybe_url_match is None: + raise ValueError( + f"Unexpected hostname structure: {host}" + ) # pragma: NO COVER + + url_match_items = maybe_url_match.groupdict() + + host = f"{url_scheme}://{host}" if not url_match_items["scheme"] else host + + super().__init__( + host=host, + credentials=credentials, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + self._session = AuthorizedSession( + self._credentials, default_host=self.DEFAULT_HOST + ) + if client_cert_source_for_mtls: + self._session.configure_mtls_channel(client_cert_source_for_mtls) + self._interceptor = interceptor or AdaptationRestInterceptor() + self._prep_wrapped_messages(client_info) + + class _CreateCustomClass(AdaptationRestStub): + def __hash__(self): + return hash("CreateCustomClass") + + __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 + } + + def __call__( + self, + request: cloud_speech_adaptation.CreateCustomClassRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> resource.CustomClass: + r"""Call the create custom class method over HTTP. + + Args: + request (~.cloud_speech_adaptation.CreateCustomClassRequest): + The request object. Message sent by the client for the ``CreateCustomClass`` + method. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.resource.CustomClass: + A set of words or phrases that + represents a common concept likely to + appear in your audio, for example a list + of passenger ship names. CustomClass + items can be substituted into + placeholders that you set in PhraseSet + phrases. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1/{parent=projects/*/locations/*}/customClasses", + "body": "*", + }, + ] + request, metadata = self._interceptor.pre_create_custom_class( + request, metadata + ) + pb_request = cloud_speech_adaptation.CreateCustomClassRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=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 = resource.CustomClass() + pb_resp = resource.CustomClass.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_create_custom_class(resp) + return resp + + class _CreatePhraseSet(AdaptationRestStub): + def __hash__(self): + return hash("CreatePhraseSet") + + __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 + } + + def __call__( + self, + request: cloud_speech_adaptation.CreatePhraseSetRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> resource.PhraseSet: + r"""Call the create phrase set method over HTTP. + + Args: + request (~.cloud_speech_adaptation.CreatePhraseSetRequest): + The request object. Message sent by the client for the ``CreatePhraseSet`` + method. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.resource.PhraseSet: + Provides "hints" to the speech + recognizer to favor specific words and + phrases in the results. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1/{parent=projects/*/locations/*}/phraseSets", + "body": "*", + }, + ] + request, metadata = self._interceptor.pre_create_phrase_set( + request, metadata + ) + pb_request = cloud_speech_adaptation.CreatePhraseSetRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=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 = resource.PhraseSet() + pb_resp = resource.PhraseSet.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_create_phrase_set(resp) + return resp + + class _DeleteCustomClass(AdaptationRestStub): + def __hash__(self): + return hash("DeleteCustomClass") + + __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 + } + + def __call__( + self, + request: cloud_speech_adaptation.DeleteCustomClassRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ): + r"""Call the delete custom class method over HTTP. + + Args: + request (~.cloud_speech_adaptation.DeleteCustomClassRequest): + The request object. Message sent by the client for the ``DeleteCustomClass`` + method. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "delete", + "uri": "/v1/{name=projects/*/locations/*/customClasses/*}", + }, + ] + request, metadata = self._interceptor.pre_delete_custom_class( + request, metadata + ) + pb_request = cloud_speech_adaptation.DeleteCustomClassRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + class _DeletePhraseSet(AdaptationRestStub): + def __hash__(self): + return hash("DeletePhraseSet") + + __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 + } + + def __call__( + self, + request: cloud_speech_adaptation.DeletePhraseSetRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ): + r"""Call the delete phrase set method over HTTP. + + Args: + request (~.cloud_speech_adaptation.DeletePhraseSetRequest): + The request object. Message sent by the client for the ``DeletePhraseSet`` + method. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "delete", + "uri": "/v1/{name=projects/*/locations/*/phraseSets/*}", + }, + ] + request, metadata = self._interceptor.pre_delete_phrase_set( + request, metadata + ) + pb_request = cloud_speech_adaptation.DeletePhraseSetRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + class _GetCustomClass(AdaptationRestStub): + def __hash__(self): + return hash("GetCustomClass") + + __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 + } + + def __call__( + self, + request: cloud_speech_adaptation.GetCustomClassRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> resource.CustomClass: + r"""Call the get custom class method over HTTP. + + Args: + request (~.cloud_speech_adaptation.GetCustomClassRequest): + The request object. Message sent by the client for the ``GetCustomClass`` + method. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.resource.CustomClass: + A set of words or phrases that + represents a common concept likely to + appear in your audio, for example a list + of passenger ship names. CustomClass + items can be substituted into + placeholders that you set in PhraseSet + phrases. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{name=projects/*/locations/*/customClasses/*}", + }, + ] + request, metadata = self._interceptor.pre_get_custom_class( + request, metadata + ) + pb_request = cloud_speech_adaptation.GetCustomClassRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # 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 = resource.CustomClass() + pb_resp = resource.CustomClass.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_custom_class(resp) + return resp + + class _GetPhraseSet(AdaptationRestStub): + def __hash__(self): + return hash("GetPhraseSet") + + __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 + } + + def __call__( + self, + request: cloud_speech_adaptation.GetPhraseSetRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> resource.PhraseSet: + r"""Call the get phrase set method over HTTP. + + Args: + request (~.cloud_speech_adaptation.GetPhraseSetRequest): + The request object. Message sent by the client for the ``GetPhraseSet`` + method. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.resource.PhraseSet: + Provides "hints" to the speech + recognizer to favor specific words and + phrases in the results. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{name=projects/*/locations/*/phraseSets/*}", + }, + ] + request, metadata = self._interceptor.pre_get_phrase_set(request, metadata) + pb_request = cloud_speech_adaptation.GetPhraseSetRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # 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 = resource.PhraseSet() + pb_resp = resource.PhraseSet.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_phrase_set(resp) + return resp + + class _ListCustomClasses(AdaptationRestStub): + def __hash__(self): + return hash("ListCustomClasses") + + __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 + } + + def __call__( + self, + request: cloud_speech_adaptation.ListCustomClassesRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> cloud_speech_adaptation.ListCustomClassesResponse: + r"""Call the list custom classes method over HTTP. + + Args: + request (~.cloud_speech_adaptation.ListCustomClassesRequest): + The request object. Message sent by the client for the ``ListCustomClasses`` + method. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.cloud_speech_adaptation.ListCustomClassesResponse: + Message returned to the client by the + ``ListCustomClasses`` method. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{parent=projects/*/locations/*}/customClasses", + }, + ] + request, metadata = self._interceptor.pre_list_custom_classes( + request, metadata + ) + pb_request = cloud_speech_adaptation.ListCustomClassesRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # 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 = cloud_speech_adaptation.ListCustomClassesResponse() + pb_resp = cloud_speech_adaptation.ListCustomClassesResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_custom_classes(resp) + return resp + + class _ListPhraseSet(AdaptationRestStub): + def __hash__(self): + return hash("ListPhraseSet") + + __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 + } + + def __call__( + self, + request: cloud_speech_adaptation.ListPhraseSetRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> cloud_speech_adaptation.ListPhraseSetResponse: + r"""Call the list phrase set method over HTTP. + + Args: + request (~.cloud_speech_adaptation.ListPhraseSetRequest): + The request object. Message sent by the client for the ``ListPhraseSet`` + method. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.cloud_speech_adaptation.ListPhraseSetResponse: + Message returned to the client by the ``ListPhraseSet`` + method. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{parent=projects/*/locations/*}/phraseSets", + }, + ] + request, metadata = self._interceptor.pre_list_phrase_set(request, metadata) + pb_request = cloud_speech_adaptation.ListPhraseSetRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # 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 = cloud_speech_adaptation.ListPhraseSetResponse() + pb_resp = cloud_speech_adaptation.ListPhraseSetResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_phrase_set(resp) + return resp + + class _UpdateCustomClass(AdaptationRestStub): + def __hash__(self): + return hash("UpdateCustomClass") + + __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 + } + + def __call__( + self, + request: cloud_speech_adaptation.UpdateCustomClassRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> resource.CustomClass: + r"""Call the update custom class method over HTTP. + + Args: + request (~.cloud_speech_adaptation.UpdateCustomClassRequest): + The request object. Message sent by the client for the ``UpdateCustomClass`` + method. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.resource.CustomClass: + A set of words or phrases that + represents a common concept likely to + appear in your audio, for example a list + of passenger ship names. CustomClass + items can be substituted into + placeholders that you set in PhraseSet + phrases. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "patch", + "uri": "/v1/{custom_class.name=projects/*/locations/*/customClasses/*}", + "body": "custom_class", + }, + ] + request, metadata = self._interceptor.pre_update_custom_class( + request, metadata + ) + pb_request = cloud_speech_adaptation.UpdateCustomClassRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=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 = resource.CustomClass() + pb_resp = resource.CustomClass.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_update_custom_class(resp) + return resp + + class _UpdatePhraseSet(AdaptationRestStub): + def __hash__(self): + return hash("UpdatePhraseSet") + + __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 + } + + def __call__( + self, + request: cloud_speech_adaptation.UpdatePhraseSetRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> resource.PhraseSet: + r"""Call the update phrase set method over HTTP. + + Args: + request (~.cloud_speech_adaptation.UpdatePhraseSetRequest): + The request object. Message sent by the client for the ``UpdatePhraseSet`` + method. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.resource.PhraseSet: + Provides "hints" to the speech + recognizer to favor specific words and + phrases in the results. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "patch", + "uri": "/v1/{phrase_set.name=projects/*/locations/*/phraseSets/*}", + "body": "phrase_set", + }, + ] + request, metadata = self._interceptor.pre_update_phrase_set( + request, metadata + ) + pb_request = cloud_speech_adaptation.UpdatePhraseSetRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=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 = resource.PhraseSet() + pb_resp = resource.PhraseSet.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_update_phrase_set(resp) + return resp + + @property + def create_custom_class( + self, + ) -> Callable[ + [cloud_speech_adaptation.CreateCustomClassRequest], resource.CustomClass + ]: + # 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._CreateCustomClass(self._session, self._host, self._interceptor) # type: ignore + + @property + def create_phrase_set( + self, + ) -> Callable[[cloud_speech_adaptation.CreatePhraseSetRequest], resource.PhraseSet]: + # 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._CreatePhraseSet(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_custom_class( + self, + ) -> Callable[[cloud_speech_adaptation.DeleteCustomClassRequest], empty_pb2.Empty]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._DeleteCustomClass(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_phrase_set( + self, + ) -> Callable[[cloud_speech_adaptation.DeletePhraseSetRequest], empty_pb2.Empty]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._DeletePhraseSet(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_custom_class( + self, + ) -> Callable[ + [cloud_speech_adaptation.GetCustomClassRequest], resource.CustomClass + ]: + # 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._GetCustomClass(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_phrase_set( + self, + ) -> Callable[[cloud_speech_adaptation.GetPhraseSetRequest], resource.PhraseSet]: + # 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._GetPhraseSet(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_custom_classes( + self, + ) -> Callable[ + [cloud_speech_adaptation.ListCustomClassesRequest], + cloud_speech_adaptation.ListCustomClassesResponse, + ]: + # 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._ListCustomClasses(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_phrase_set( + self, + ) -> Callable[ + [cloud_speech_adaptation.ListPhraseSetRequest], + cloud_speech_adaptation.ListPhraseSetResponse, + ]: + # 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._ListPhraseSet(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_custom_class( + self, + ) -> Callable[ + [cloud_speech_adaptation.UpdateCustomClassRequest], resource.CustomClass + ]: + # 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._UpdateCustomClass(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_phrase_set( + self, + ) -> Callable[[cloud_speech_adaptation.UpdatePhraseSetRequest], resource.PhraseSet]: + # 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._UpdatePhraseSet(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_operation(self): + return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore + + class _GetOperation(AdaptationRestStub): + def __call__( + self, + request: operations_pb2.GetOperationRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + + r"""Call the get operation method over HTTP. + + Args: + request (operations_pb2.GetOperationRequest): + The request object for GetOperation method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + operations_pb2.Operation: Response from GetOperation method. + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/operations/{name=**}", + }, + ] + + request, metadata = self._interceptor.pre_get_operation(request, metadata) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + resp = operations_pb2.Operation() + resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = self._interceptor.post_get_operation(resp) + return resp + + @property + def list_operations(self): + return self._ListOperations(self._session, self._host, self._interceptor) # type: ignore + + class _ListOperations(AdaptationRestStub): + def __call__( + self, + request: operations_pb2.ListOperationsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.ListOperationsResponse: + + r"""Call the list operations method over HTTP. + + Args: + request (operations_pb2.ListOperationsRequest): + The request object for ListOperations method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + operations_pb2.ListOperationsResponse: Response from ListOperations method. + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/operations", + }, + ] + + request, metadata = self._interceptor.pre_list_operations(request, metadata) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + resp = operations_pb2.ListOperationsResponse() + resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = self._interceptor.post_list_operations(resp) + return resp + + @property + def kind(self) -> str: + return "rest" + + def close(self): + self._session.close() + + +__all__ = ("AdaptationRestTransport",) diff --git a/google/cloud/speech_v1/services/speech/client.py b/google/cloud/speech_v1/services/speech/client.py index d236fefa..8870959e 100644 --- a/google/cloud/speech_v1/services/speech/client.py +++ b/google/cloud/speech_v1/services/speech/client.py @@ -57,6 +57,7 @@ from .transports.base import SpeechTransport, DEFAULT_CLIENT_INFO from .transports.grpc import SpeechGrpcTransport from .transports.grpc_asyncio import SpeechGrpcAsyncIOTransport +from .transports.rest import SpeechRestTransport class SpeechClientMeta(type): @@ -70,6 +71,7 @@ class SpeechClientMeta(type): _transport_registry = OrderedDict() # type: Dict[str, Type[SpeechTransport]] _transport_registry["grpc"] = SpeechGrpcTransport _transport_registry["grpc_asyncio"] = SpeechGrpcAsyncIOTransport + _transport_registry["rest"] = SpeechRestTransport def get_transport_class( cls, diff --git a/google/cloud/speech_v1/services/speech/transports/__init__.py b/google/cloud/speech_v1/services/speech/transports/__init__.py index 4f7834ee..ce902d84 100644 --- a/google/cloud/speech_v1/services/speech/transports/__init__.py +++ b/google/cloud/speech_v1/services/speech/transports/__init__.py @@ -19,15 +19,20 @@ from .base import SpeechTransport from .grpc import SpeechGrpcTransport from .grpc_asyncio import SpeechGrpcAsyncIOTransport +from .rest import SpeechRestTransport +from .rest import SpeechRestInterceptor # Compile a registry of transports. _transport_registry = OrderedDict() # type: Dict[str, Type[SpeechTransport]] _transport_registry["grpc"] = SpeechGrpcTransport _transport_registry["grpc_asyncio"] = SpeechGrpcAsyncIOTransport +_transport_registry["rest"] = SpeechRestTransport __all__ = ( "SpeechTransport", "SpeechGrpcTransport", "SpeechGrpcAsyncIOTransport", + "SpeechRestTransport", + "SpeechRestInterceptor", ) diff --git a/google/cloud/speech_v1/services/speech/transports/rest.py b/google/cloud/speech_v1/services/speech/transports/rest.py new file mode 100644 index 00000000..39a179ef --- /dev/null +++ b/google/cloud/speech_v1/services/speech/transports/rest.py @@ -0,0 +1,709 @@ +# -*- coding: utf-8 -*- +# 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. +# + +from google.auth.transport.requests import AuthorizedSession # type: ignore +import json # type: ignore +import grpc # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.api_core import exceptions as core_exceptions +from google.api_core import retry as retries +from google.api_core import rest_helpers +from google.api_core import rest_streaming +from google.api_core import path_template +from google.api_core import gapic_v1 + +from google.protobuf import json_format +from google.api_core import operations_v1 +from google.longrunning import operations_pb2 +from requests import __version__ as requests_version +import dataclasses +import re +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union +import warnings + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + + +from google.cloud.speech_v1.types import cloud_speech +from google.longrunning import operations_pb2 # type: ignore + +from .base import SpeechTransport, DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, + grpc_version=None, + rest_version=requests_version, +) + + +class SpeechRestInterceptor: + """Interceptor for Speech. + + Interceptors are used to manipulate requests, request metadata, and responses + in arbitrary ways. + Example use cases include: + * Logging + * Verifying requests according to service or custom semantics + * Stripping extraneous information from responses + + These use cases and more can be enabled by injecting an + instance of a custom subclass when constructing the SpeechRestTransport. + + .. code-block:: python + class MyCustomSpeechInterceptor(SpeechRestInterceptor): + def pre_long_running_recognize(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_long_running_recognize(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_recognize(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_recognize(self, response): + logging.log(f"Received response: {response}") + return response + + transport = SpeechRestTransport(interceptor=MyCustomSpeechInterceptor()) + client = SpeechClient(transport=transport) + + + """ + + def pre_long_running_recognize( + self, + request: cloud_speech.LongRunningRecognizeRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[cloud_speech.LongRunningRecognizeRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for long_running_recognize + + Override in a subclass to manipulate the request or metadata + before they are sent to the Speech server. + """ + return request, metadata + + def post_long_running_recognize( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for long_running_recognize + + Override in a subclass to manipulate the response + after it is returned by the Speech server but before + it is returned to user code. + """ + return response + + def pre_recognize( + self, + request: cloud_speech.RecognizeRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[cloud_speech.RecognizeRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for recognize + + Override in a subclass to manipulate the request or metadata + before they are sent to the Speech server. + """ + return request, metadata + + def post_recognize( + self, response: cloud_speech.RecognizeResponse + ) -> cloud_speech.RecognizeResponse: + """Post-rpc interceptor for recognize + + Override in a subclass to manipulate the response + after it is returned by the Speech server but before + it is returned to user code. + """ + return response + + def pre_get_operation( + self, + request: operations_pb2.GetOperationRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[operations_pb2.GetOperationRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_operation + + Override in a subclass to manipulate the request or metadata + before they are sent to the Speech server. + """ + return request, metadata + + def post_get_operation( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for get_operation + + Override in a subclass to manipulate the response + after it is returned by the Speech server but before + it is returned to user code. + """ + return response + + def pre_list_operations( + self, + request: operations_pb2.ListOperationsRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[operations_pb2.ListOperationsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_operations + + Override in a subclass to manipulate the request or metadata + before they are sent to the Speech server. + """ + return request, metadata + + def post_list_operations( + self, response: operations_pb2.ListOperationsResponse + ) -> operations_pb2.ListOperationsResponse: + """Post-rpc interceptor for list_operations + + Override in a subclass to manipulate the response + after it is returned by the Speech server but before + it is returned to user code. + """ + return response + + +@dataclasses.dataclass +class SpeechRestStub: + _session: AuthorizedSession + _host: str + _interceptor: SpeechRestInterceptor + + +class SpeechRestTransport(SpeechTransport): + """REST backend transport for Speech. + + Service that implements Google Cloud Speech API. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends JSON representations of protocol buffers over HTTP/1.1 + + """ + + def __init__( + self, + *, + host: str = "speech.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + url_scheme: str = "https", + interceptor: Optional[SpeechRestInterceptor] = None, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + client_cert_source_for_mtls (Callable[[], Tuple[bytes, bytes]]): Client + certificate to configure mutual TLS HTTP channel. It is ignored + if ``channel`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you are developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + url_scheme: the protocol scheme for the API endpoint. Normally + "https", but for testing or local servers, + "http" can be specified. + """ + # Run the base constructor + # TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc. + # TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the + # credentials object + maybe_url_match = re.match("^(?Phttp(?:s)?://)?(?P.*)$", host) + if maybe_url_match is None: + raise ValueError( + f"Unexpected hostname structure: {host}" + ) # pragma: NO COVER + + url_match_items = maybe_url_match.groupdict() + + host = f"{url_scheme}://{host}" if not url_match_items["scheme"] else host + + super().__init__( + host=host, + credentials=credentials, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + self._session = AuthorizedSession( + self._credentials, default_host=self.DEFAULT_HOST + ) + self._operations_client: Optional[operations_v1.AbstractOperationsClient] = None + if client_cert_source_for_mtls: + self._session.configure_mtls_channel(client_cert_source_for_mtls) + self._interceptor = interceptor or SpeechRestInterceptor() + self._prep_wrapped_messages(client_info) + + @property + def operations_client(self) -> operations_v1.AbstractOperationsClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Only create a new client if we do not already have one. + if self._operations_client is None: + http_options: Dict[str, List[Dict[str, str]]] = { + "google.longrunning.Operations.GetOperation": [ + { + "method": "get", + "uri": "/v1/operations/{name=**}", + }, + ], + "google.longrunning.Operations.ListOperations": [ + { + "method": "get", + "uri": "/v1/operations", + }, + ], + } + + rest_transport = operations_v1.OperationsRestTransport( + host=self._host, + # use the credentials which are saved + credentials=self._credentials, + scopes=self._scopes, + http_options=http_options, + path_prefix="v1", + ) + + self._operations_client = operations_v1.AbstractOperationsClient( + transport=rest_transport + ) + + # Return the client from cache. + return self._operations_client + + class _LongRunningRecognize(SpeechRestStub): + def __hash__(self): + return hash("LongRunningRecognize") + + __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 + } + + def __call__( + self, + request: cloud_speech.LongRunningRecognizeRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + r"""Call the long running recognize method over HTTP. + + Args: + request (~.cloud_speech.LongRunningRecognizeRequest): + The request object. The top-level message sent by the client for the + ``LongRunningRecognize`` method. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1/speech:longrunningrecognize", + "body": "*", + }, + ] + request, metadata = self._interceptor.pre_long_running_recognize( + request, metadata + ) + pb_request = cloud_speech.LongRunningRecognizeRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=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_long_running_recognize(resp) + return resp + + class _Recognize(SpeechRestStub): + def __hash__(self): + return hash("Recognize") + + __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 + } + + def __call__( + self, + request: cloud_speech.RecognizeRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> cloud_speech.RecognizeResponse: + r"""Call the recognize method over HTTP. + + Args: + request (~.cloud_speech.RecognizeRequest): + The request object. The top-level message sent by the client for the + ``Recognize`` method. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.cloud_speech.RecognizeResponse: + The only message returned to the client by the + ``Recognize`` method. It contains the result as zero or + more sequential ``SpeechRecognitionResult`` messages. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1/speech:recognize", + "body": "*", + }, + ] + request, metadata = self._interceptor.pre_recognize(request, metadata) + pb_request = cloud_speech.RecognizeRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=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 = cloud_speech.RecognizeResponse() + pb_resp = cloud_speech.RecognizeResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_recognize(resp) + return resp + + class _StreamingRecognize(SpeechRestStub): + def __hash__(self): + return hash("StreamingRecognize") + + def __call__( + self, + request: cloud_speech.StreamingRecognizeRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> rest_streaming.ResponseIterator: + raise NotImplementedError( + "Method StreamingRecognize is not available over REST transport" + ) + + @property + def long_running_recognize( + self, + ) -> Callable[[cloud_speech.LongRunningRecognizeRequest], 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._LongRunningRecognize(self._session, self._host, self._interceptor) # type: ignore + + @property + def recognize( + self, + ) -> Callable[[cloud_speech.RecognizeRequest], cloud_speech.RecognizeResponse]: + # 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._Recognize(self._session, self._host, self._interceptor) # type: ignore + + @property + def streaming_recognize( + self, + ) -> Callable[ + [cloud_speech.StreamingRecognizeRequest], + cloud_speech.StreamingRecognizeResponse, + ]: + # 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._StreamingRecognize(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_operation(self): + return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore + + class _GetOperation(SpeechRestStub): + def __call__( + self, + request: operations_pb2.GetOperationRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + + r"""Call the get operation method over HTTP. + + Args: + request (operations_pb2.GetOperationRequest): + The request object for GetOperation method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + operations_pb2.Operation: Response from GetOperation method. + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/operations/{name=**}", + }, + ] + + request, metadata = self._interceptor.pre_get_operation(request, metadata) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + resp = operations_pb2.Operation() + resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = self._interceptor.post_get_operation(resp) + return resp + + @property + def list_operations(self): + return self._ListOperations(self._session, self._host, self._interceptor) # type: ignore + + class _ListOperations(SpeechRestStub): + def __call__( + self, + request: operations_pb2.ListOperationsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.ListOperationsResponse: + + r"""Call the list operations method over HTTP. + + Args: + request (operations_pb2.ListOperationsRequest): + The request object for ListOperations method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + operations_pb2.ListOperationsResponse: Response from ListOperations method. + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/operations", + }, + ] + + request, metadata = self._interceptor.pre_list_operations(request, metadata) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + resp = operations_pb2.ListOperationsResponse() + resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = self._interceptor.post_list_operations(resp) + return resp + + @property + def kind(self) -> str: + return "rest" + + def close(self): + self._session.close() + + +__all__ = ("SpeechRestTransport",) diff --git a/google/cloud/speech_v1/types/cloud_speech.py b/google/cloud/speech_v1/types/cloud_speech.py index 583c0187..8f812c4a 100644 --- a/google/cloud/speech_v1/types/cloud_speech.py +++ b/google/cloud/speech_v1/types/cloud_speech.py @@ -13,6 +13,8 @@ # See the License for the specific language governing permissions and # limitations under the License. # +from __future__ import annotations + from typing import MutableMapping, MutableSequence import proto # type: ignore @@ -223,8 +225,39 @@ class StreamingRecognitionConfig(proto.Message): returned as they become available (these interim results are indicated with the ``is_final=false`` flag). If ``false`` or omitted, only ``is_final=true`` result(s) are returned. + enable_voice_activity_events (bool): + If ``true``, responses with voice activity speech events + will be returned as they are detected. + voice_activity_timeout (google.cloud.speech_v1.types.StreamingRecognitionConfig.VoiceActivityTimeout): + If set, the server will automatically close the stream after + the specified duration has elapsed after the last + VOICE_ACTIVITY speech event has been sent. The field + ``voice_activity_events`` must also be set to true. """ + class VoiceActivityTimeout(proto.Message): + r"""Events that a timeout can be set on for voice activity. + + Attributes: + speech_start_timeout (google.protobuf.duration_pb2.Duration): + Duration to timeout the stream if no speech + begins. + speech_end_timeout (google.protobuf.duration_pb2.Duration): + Duration to timeout the stream after speech + ends. + """ + + speech_start_timeout: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=1, + message=duration_pb2.Duration, + ) + speech_end_timeout: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=2, + message=duration_pb2.Duration, + ) + config: "RecognitionConfig" = proto.Field( proto.MESSAGE, number=1, @@ -238,6 +271,15 @@ class StreamingRecognitionConfig(proto.Message): proto.BOOL, number=3, ) + enable_voice_activity_events: bool = proto.Field( + proto.BOOL, + number=5, + ) + voice_activity_timeout: VoiceActivityTimeout = proto.Field( + proto.MESSAGE, + number=6, + message=VoiceActivityTimeout, + ) class RecognitionConfig(proto.Message): @@ -1146,6 +1188,9 @@ class StreamingRecognizeResponse(proto.Message): ``is_final=false`` results (the interim results). speech_event_type (google.cloud.speech_v1.types.StreamingRecognizeResponse.SpeechEventType): Indicates the type of speech event. + speech_event_time (google.protobuf.duration_pb2.Duration): + Time offset between the beginning of the + audio and event emission. total_billed_time (google.protobuf.duration_pb2.Duration): When available, billed audio seconds for the stream. Set only if this is the last response in @@ -1174,9 +1219,30 @@ class SpeechEventType(proto.Enum): additional results until the server closes the gRPC connection. This event is only sent if ``single_utterance`` was set to ``true``, and is not used otherwise. + SPEECH_ACTIVITY_BEGIN (2): + This event indicates that the server has detected the + beginning of human voice activity in the stream. This event + can be returned multiple times if speech starts and stops + repeatedly throughout the stream. This event is only sent if + ``voice_activity_events`` is set to true. + SPEECH_ACTIVITY_END (3): + This event indicates that the server has detected the end of + human voice activity in the stream. This event can be + returned multiple times if speech starts and stops + repeatedly throughout the stream. This event is only sent if + ``voice_activity_events`` is set to true. + SPEECH_ACTIVITY_TIMEOUT (4): + This event indicates that the user-set + timeout for speech activity begin or end has + exceeded. Upon receiving this event, the client + is expected to send a half close. Further audio + will not be processed. """ SPEECH_EVENT_UNSPECIFIED = 0 END_OF_SINGLE_UTTERANCE = 1 + SPEECH_ACTIVITY_BEGIN = 2 + SPEECH_ACTIVITY_END = 3 + SPEECH_ACTIVITY_TIMEOUT = 4 error: status_pb2.Status = proto.Field( proto.MESSAGE, @@ -1193,6 +1259,11 @@ class SpeechEventType(proto.Enum): number=4, enum=SpeechEventType, ) + speech_event_time: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=8, + message=duration_pb2.Duration, + ) total_billed_time: duration_pb2.Duration = proto.Field( proto.MESSAGE, number=5, diff --git a/google/cloud/speech_v1/types/cloud_speech_adaptation.py b/google/cloud/speech_v1/types/cloud_speech_adaptation.py index d2d9a630..91d06422 100644 --- a/google/cloud/speech_v1/types/cloud_speech_adaptation.py +++ b/google/cloud/speech_v1/types/cloud_speech_adaptation.py @@ -13,6 +13,8 @@ # See the License for the specific language governing permissions and # limitations under the License. # +from __future__ import annotations + from typing import MutableMapping, MutableSequence import proto # type: ignore diff --git a/google/cloud/speech_v1/types/resource.py b/google/cloud/speech_v1/types/resource.py index 29206d08..11c53a12 100644 --- a/google/cloud/speech_v1/types/resource.py +++ b/google/cloud/speech_v1/types/resource.py @@ -13,6 +13,8 @@ # See the License for the specific language governing permissions and # limitations under the License. # +from __future__ import annotations + from typing import MutableMapping, MutableSequence import proto # type: ignore diff --git a/google/cloud/speech_v1p1beta1/gapic_metadata.json b/google/cloud/speech_v1p1beta1/gapic_metadata.json index 3561c102..a1a3a774 100644 --- a/google/cloud/speech_v1p1beta1/gapic_metadata.json +++ b/google/cloud/speech_v1p1beta1/gapic_metadata.json @@ -116,6 +116,61 @@ ] } } + }, + "rest": { + "libraryClient": "AdaptationClient", + "rpcs": { + "CreateCustomClass": { + "methods": [ + "create_custom_class" + ] + }, + "CreatePhraseSet": { + "methods": [ + "create_phrase_set" + ] + }, + "DeleteCustomClass": { + "methods": [ + "delete_custom_class" + ] + }, + "DeletePhraseSet": { + "methods": [ + "delete_phrase_set" + ] + }, + "GetCustomClass": { + "methods": [ + "get_custom_class" + ] + }, + "GetPhraseSet": { + "methods": [ + "get_phrase_set" + ] + }, + "ListCustomClasses": { + "methods": [ + "list_custom_classes" + ] + }, + "ListPhraseSet": { + "methods": [ + "list_phrase_set" + ] + }, + "UpdateCustomClass": { + "methods": [ + "update_custom_class" + ] + }, + "UpdatePhraseSet": { + "methods": [ + "update_phrase_set" + ] + } + } } } }, @@ -160,6 +215,26 @@ ] } } + }, + "rest": { + "libraryClient": "SpeechClient", + "rpcs": { + "LongRunningRecognize": { + "methods": [ + "long_running_recognize" + ] + }, + "Recognize": { + "methods": [ + "recognize" + ] + }, + "StreamingRecognize": { + "methods": [ + "streaming_recognize" + ] + } + } } } } diff --git a/google/cloud/speech_v1p1beta1/gapic_version.py b/google/cloud/speech_v1p1beta1/gapic_version.py index 36f3d159..f09943f6 100644 --- a/google/cloud/speech_v1p1beta1/gapic_version.py +++ b/google/cloud/speech_v1p1beta1/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "2.17.3" # {x-release-please-version} +__version__ = "2.18.0" # {x-release-please-version} diff --git a/google/cloud/speech_v1p1beta1/services/adaptation/async_client.py b/google/cloud/speech_v1p1beta1/services/adaptation/async_client.py index ae9ba0a1..5eeb1abc 100644 --- a/google/cloud/speech_v1p1beta1/services/adaptation/async_client.py +++ b/google/cloud/speech_v1p1beta1/services/adaptation/async_client.py @@ -45,6 +45,7 @@ from google.cloud.speech_v1p1beta1.services.adaptation import pagers from google.cloud.speech_v1p1beta1.types import cloud_speech_adaptation from google.cloud.speech_v1p1beta1.types import resource +from google.longrunning import operations_pb2 from google.protobuf import field_mask_pb2 # type: ignore from .transports.base import AdaptationTransport, DEFAULT_CLIENT_INFO from .transports.grpc_asyncio import AdaptationGrpcAsyncIOTransport @@ -1429,6 +1430,114 @@ async def sample_delete_custom_class(): metadata=metadata, ) + async def list_operations( + self, + request: Optional[operations_pb2.ListOperationsRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.ListOperationsResponse: + r"""Lists operations that match the specified filter in the request. + + Args: + request (:class:`~.operations_pb2.ListOperationsRequest`): + The request object. Request message for + `ListOperations` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.operations_pb2.ListOperationsResponse: + Response message for ``ListOperations`` method. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.ListOperationsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._client._transport.list_operations, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # 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),)), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_operation( + self, + request: Optional[operations_pb2.GetOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + r"""Gets the latest state of a long-running operation. + + Args: + request (:class:`~.operations_pb2.GetOperationRequest`): + The request object. Request message for + `GetOperation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.operations_pb2.Operation: + An ``Operation`` object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.GetOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._client._transport.get_operation, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # 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),)), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + async def __aenter__(self): return self diff --git a/google/cloud/speech_v1p1beta1/services/adaptation/client.py b/google/cloud/speech_v1p1beta1/services/adaptation/client.py index c412c635..b910111a 100644 --- a/google/cloud/speech_v1p1beta1/services/adaptation/client.py +++ b/google/cloud/speech_v1p1beta1/services/adaptation/client.py @@ -49,10 +49,12 @@ from google.cloud.speech_v1p1beta1.services.adaptation import pagers from google.cloud.speech_v1p1beta1.types import cloud_speech_adaptation from google.cloud.speech_v1p1beta1.types import resource +from google.longrunning import operations_pb2 from google.protobuf import field_mask_pb2 # type: ignore from .transports.base import AdaptationTransport, DEFAULT_CLIENT_INFO from .transports.grpc import AdaptationGrpcTransport from .transports.grpc_asyncio import AdaptationGrpcAsyncIOTransport +from .transports.rest import AdaptationRestTransport class AdaptationClientMeta(type): @@ -66,6 +68,7 @@ class AdaptationClientMeta(type): _transport_registry = OrderedDict() # type: Dict[str, Type[AdaptationTransport]] _transport_registry["grpc"] = AdaptationGrpcTransport _transport_registry["grpc_asyncio"] = AdaptationGrpcAsyncIOTransport + _transport_registry["rest"] = AdaptationRestTransport def get_transport_class( cls, @@ -1693,6 +1696,114 @@ def __exit__(self, type, value, traceback): """ self.transport.close() + def list_operations( + self, + request: Optional[operations_pb2.ListOperationsRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.ListOperationsResponse: + r"""Lists operations that match the specified filter in the request. + + Args: + request (:class:`~.operations_pb2.ListOperationsRequest`): + The request object. Request message for + `ListOperations` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.operations_pb2.ListOperationsResponse: + Response message for ``ListOperations`` method. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.ListOperationsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.list_operations, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # 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),)), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_operation( + self, + request: Optional[operations_pb2.GetOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + r"""Gets the latest state of a long-running operation. + + Args: + request (:class:`~.operations_pb2.GetOperationRequest`): + The request object. Request message for + `GetOperation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.operations_pb2.Operation: + An ``Operation`` object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.GetOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.get_operation, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # 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),)), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( gapic_version=package_version.__version__ diff --git a/google/cloud/speech_v1p1beta1/services/adaptation/transports/__init__.py b/google/cloud/speech_v1p1beta1/services/adaptation/transports/__init__.py index 1a966428..8a945154 100644 --- a/google/cloud/speech_v1p1beta1/services/adaptation/transports/__init__.py +++ b/google/cloud/speech_v1p1beta1/services/adaptation/transports/__init__.py @@ -19,15 +19,20 @@ from .base import AdaptationTransport from .grpc import AdaptationGrpcTransport from .grpc_asyncio import AdaptationGrpcAsyncIOTransport +from .rest import AdaptationRestTransport +from .rest import AdaptationRestInterceptor # Compile a registry of transports. _transport_registry = OrderedDict() # type: Dict[str, Type[AdaptationTransport]] _transport_registry["grpc"] = AdaptationGrpcTransport _transport_registry["grpc_asyncio"] = AdaptationGrpcAsyncIOTransport +_transport_registry["rest"] = AdaptationRestTransport __all__ = ( "AdaptationTransport", "AdaptationGrpcTransport", "AdaptationGrpcAsyncIOTransport", + "AdaptationRestTransport", + "AdaptationRestInterceptor", ) diff --git a/google/cloud/speech_v1p1beta1/services/adaptation/transports/base.py b/google/cloud/speech_v1p1beta1/services/adaptation/transports/base.py index 861402a3..17f96f3c 100644 --- a/google/cloud/speech_v1p1beta1/services/adaptation/transports/base.py +++ b/google/cloud/speech_v1p1beta1/services/adaptation/transports/base.py @@ -28,6 +28,7 @@ from google.cloud.speech_v1p1beta1.types import cloud_speech_adaptation from google.cloud.speech_v1p1beta1.types import resource +from google.longrunning import operations_pb2 from google.protobuf import empty_pb2 # type: ignore DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( @@ -282,6 +283,27 @@ def delete_custom_class( ]: raise NotImplementedError() + @property + def list_operations( + self, + ) -> Callable[ + [operations_pb2.ListOperationsRequest], + Union[ + operations_pb2.ListOperationsResponse, + Awaitable[operations_pb2.ListOperationsResponse], + ], + ]: + raise NotImplementedError() + + @property + def get_operation( + self, + ) -> Callable[ + [operations_pb2.GetOperationRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + @property def kind(self) -> str: raise NotImplementedError() diff --git a/google/cloud/speech_v1p1beta1/services/adaptation/transports/grpc.py b/google/cloud/speech_v1p1beta1/services/adaptation/transports/grpc.py index 7e10be5c..7fdfaa48 100644 --- a/google/cloud/speech_v1p1beta1/services/adaptation/transports/grpc.py +++ b/google/cloud/speech_v1p1beta1/services/adaptation/transports/grpc.py @@ -26,6 +26,7 @@ from google.cloud.speech_v1p1beta1.types import cloud_speech_adaptation from google.cloud.speech_v1p1beta1.types import resource +from google.longrunning import operations_pb2 from google.protobuf import empty_pb2 # type: ignore from .base import AdaptationTransport, DEFAULT_CLIENT_INFO @@ -509,6 +510,42 @@ def delete_custom_class( def close(self): self.grpc_channel.close() + @property + def get_operation( + self, + ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: + r"""Return a callable for the get_operation method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_operation" not in self._stubs: + self._stubs["get_operation"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/GetOperation", + request_serializer=operations_pb2.GetOperationRequest.SerializeToString, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["get_operation"] + + @property + def list_operations( + self, + ) -> Callable[ + [operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse + ]: + r"""Return a callable for the list_operations method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_operations" not in self._stubs: + self._stubs["list_operations"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/ListOperations", + request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, + response_deserializer=operations_pb2.ListOperationsResponse.FromString, + ) + return self._stubs["list_operations"] + @property def kind(self) -> str: return "grpc" diff --git a/google/cloud/speech_v1p1beta1/services/adaptation/transports/grpc_asyncio.py b/google/cloud/speech_v1p1beta1/services/adaptation/transports/grpc_asyncio.py index d620d637..a1dccef4 100644 --- a/google/cloud/speech_v1p1beta1/services/adaptation/transports/grpc_asyncio.py +++ b/google/cloud/speech_v1p1beta1/services/adaptation/transports/grpc_asyncio.py @@ -26,6 +26,7 @@ from google.cloud.speech_v1p1beta1.types import cloud_speech_adaptation from google.cloud.speech_v1p1beta1.types import resource +from google.longrunning import operations_pb2 from google.protobuf import empty_pb2 # type: ignore from .base import AdaptationTransport, DEFAULT_CLIENT_INFO from .grpc import AdaptationGrpcTransport @@ -524,5 +525,41 @@ def delete_custom_class( def close(self): return self.grpc_channel.close() + @property + def get_operation( + self, + ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: + r"""Return a callable for the get_operation method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_operation" not in self._stubs: + self._stubs["get_operation"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/GetOperation", + request_serializer=operations_pb2.GetOperationRequest.SerializeToString, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["get_operation"] + + @property + def list_operations( + self, + ) -> Callable[ + [operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse + ]: + r"""Return a callable for the list_operations method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_operations" not in self._stubs: + self._stubs["list_operations"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/ListOperations", + request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, + response_deserializer=operations_pb2.ListOperationsResponse.FromString, + ) + return self._stubs["list_operations"] + __all__ = ("AdaptationGrpcAsyncIOTransport",) diff --git a/google/cloud/speech_v1p1beta1/services/adaptation/transports/rest.py b/google/cloud/speech_v1p1beta1/services/adaptation/transports/rest.py new file mode 100644 index 00000000..d14f957f --- /dev/null +++ b/google/cloud/speech_v1p1beta1/services/adaptation/transports/rest.py @@ -0,0 +1,1691 @@ +# -*- coding: utf-8 -*- +# 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. +# + +from google.auth.transport.requests import AuthorizedSession # type: ignore +import json # type: ignore +import grpc # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.api_core import exceptions as core_exceptions +from google.api_core import retry as retries +from google.api_core import rest_helpers +from google.api_core import rest_streaming +from google.api_core import path_template +from google.api_core import gapic_v1 + +from google.protobuf import json_format +from google.longrunning import operations_pb2 +from requests import __version__ as requests_version +import dataclasses +import re +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union +import warnings + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + + +from google.cloud.speech_v1p1beta1.types import cloud_speech_adaptation +from google.cloud.speech_v1p1beta1.types import resource +from google.protobuf import empty_pb2 # type: ignore + +from .base import AdaptationTransport, DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, + grpc_version=None, + rest_version=requests_version, +) + + +class AdaptationRestInterceptor: + """Interceptor for Adaptation. + + Interceptors are used to manipulate requests, request metadata, and responses + in arbitrary ways. + Example use cases include: + * Logging + * Verifying requests according to service or custom semantics + * Stripping extraneous information from responses + + These use cases and more can be enabled by injecting an + instance of a custom subclass when constructing the AdaptationRestTransport. + + .. code-block:: python + class MyCustomAdaptationInterceptor(AdaptationRestInterceptor): + def pre_create_custom_class(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_custom_class(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_create_phrase_set(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_phrase_set(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_delete_custom_class(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def pre_delete_phrase_set(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def pre_get_custom_class(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_custom_class(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_phrase_set(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_phrase_set(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_custom_classes(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_custom_classes(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_phrase_set(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_phrase_set(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_custom_class(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_custom_class(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_phrase_set(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_phrase_set(self, response): + logging.log(f"Received response: {response}") + return response + + transport = AdaptationRestTransport(interceptor=MyCustomAdaptationInterceptor()) + client = AdaptationClient(transport=transport) + + + """ + + def pre_create_custom_class( + self, + request: cloud_speech_adaptation.CreateCustomClassRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[ + cloud_speech_adaptation.CreateCustomClassRequest, Sequence[Tuple[str, str]] + ]: + """Pre-rpc interceptor for create_custom_class + + Override in a subclass to manipulate the request or metadata + before they are sent to the Adaptation server. + """ + return request, metadata + + def post_create_custom_class( + self, response: resource.CustomClass + ) -> resource.CustomClass: + """Post-rpc interceptor for create_custom_class + + Override in a subclass to manipulate the response + after it is returned by the Adaptation server but before + it is returned to user code. + """ + return response + + def pre_create_phrase_set( + self, + request: cloud_speech_adaptation.CreatePhraseSetRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[ + cloud_speech_adaptation.CreatePhraseSetRequest, Sequence[Tuple[str, str]] + ]: + """Pre-rpc interceptor for create_phrase_set + + Override in a subclass to manipulate the request or metadata + before they are sent to the Adaptation server. + """ + return request, metadata + + def post_create_phrase_set( + self, response: resource.PhraseSet + ) -> resource.PhraseSet: + """Post-rpc interceptor for create_phrase_set + + Override in a subclass to manipulate the response + after it is returned by the Adaptation server but before + it is returned to user code. + """ + return response + + def pre_delete_custom_class( + self, + request: cloud_speech_adaptation.DeleteCustomClassRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[ + cloud_speech_adaptation.DeleteCustomClassRequest, Sequence[Tuple[str, str]] + ]: + """Pre-rpc interceptor for delete_custom_class + + Override in a subclass to manipulate the request or metadata + before they are sent to the Adaptation server. + """ + return request, metadata + + def pre_delete_phrase_set( + self, + request: cloud_speech_adaptation.DeletePhraseSetRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[ + cloud_speech_adaptation.DeletePhraseSetRequest, Sequence[Tuple[str, str]] + ]: + """Pre-rpc interceptor for delete_phrase_set + + Override in a subclass to manipulate the request or metadata + before they are sent to the Adaptation server. + """ + return request, metadata + + def pre_get_custom_class( + self, + request: cloud_speech_adaptation.GetCustomClassRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[ + cloud_speech_adaptation.GetCustomClassRequest, Sequence[Tuple[str, str]] + ]: + """Pre-rpc interceptor for get_custom_class + + Override in a subclass to manipulate the request or metadata + before they are sent to the Adaptation server. + """ + return request, metadata + + def post_get_custom_class( + self, response: resource.CustomClass + ) -> resource.CustomClass: + """Post-rpc interceptor for get_custom_class + + Override in a subclass to manipulate the response + after it is returned by the Adaptation server but before + it is returned to user code. + """ + return response + + def pre_get_phrase_set( + self, + request: cloud_speech_adaptation.GetPhraseSetRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[cloud_speech_adaptation.GetPhraseSetRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_phrase_set + + Override in a subclass to manipulate the request or metadata + before they are sent to the Adaptation server. + """ + return request, metadata + + def post_get_phrase_set(self, response: resource.PhraseSet) -> resource.PhraseSet: + """Post-rpc interceptor for get_phrase_set + + Override in a subclass to manipulate the response + after it is returned by the Adaptation server but before + it is returned to user code. + """ + return response + + def pre_list_custom_classes( + self, + request: cloud_speech_adaptation.ListCustomClassesRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[ + cloud_speech_adaptation.ListCustomClassesRequest, Sequence[Tuple[str, str]] + ]: + """Pre-rpc interceptor for list_custom_classes + + Override in a subclass to manipulate the request or metadata + before they are sent to the Adaptation server. + """ + return request, metadata + + def post_list_custom_classes( + self, response: cloud_speech_adaptation.ListCustomClassesResponse + ) -> cloud_speech_adaptation.ListCustomClassesResponse: + """Post-rpc interceptor for list_custom_classes + + Override in a subclass to manipulate the response + after it is returned by the Adaptation server but before + it is returned to user code. + """ + return response + + def pre_list_phrase_set( + self, + request: cloud_speech_adaptation.ListPhraseSetRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[cloud_speech_adaptation.ListPhraseSetRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_phrase_set + + Override in a subclass to manipulate the request or metadata + before they are sent to the Adaptation server. + """ + return request, metadata + + def post_list_phrase_set( + self, response: cloud_speech_adaptation.ListPhraseSetResponse + ) -> cloud_speech_adaptation.ListPhraseSetResponse: + """Post-rpc interceptor for list_phrase_set + + Override in a subclass to manipulate the response + after it is returned by the Adaptation server but before + it is returned to user code. + """ + return response + + def pre_update_custom_class( + self, + request: cloud_speech_adaptation.UpdateCustomClassRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[ + cloud_speech_adaptation.UpdateCustomClassRequest, Sequence[Tuple[str, str]] + ]: + """Pre-rpc interceptor for update_custom_class + + Override in a subclass to manipulate the request or metadata + before they are sent to the Adaptation server. + """ + return request, metadata + + def post_update_custom_class( + self, response: resource.CustomClass + ) -> resource.CustomClass: + """Post-rpc interceptor for update_custom_class + + Override in a subclass to manipulate the response + after it is returned by the Adaptation server but before + it is returned to user code. + """ + return response + + def pre_update_phrase_set( + self, + request: cloud_speech_adaptation.UpdatePhraseSetRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[ + cloud_speech_adaptation.UpdatePhraseSetRequest, Sequence[Tuple[str, str]] + ]: + """Pre-rpc interceptor for update_phrase_set + + Override in a subclass to manipulate the request or metadata + before they are sent to the Adaptation server. + """ + return request, metadata + + def post_update_phrase_set( + self, response: resource.PhraseSet + ) -> resource.PhraseSet: + """Post-rpc interceptor for update_phrase_set + + Override in a subclass to manipulate the response + after it is returned by the Adaptation server but before + it is returned to user code. + """ + return response + + def pre_get_operation( + self, + request: operations_pb2.GetOperationRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[operations_pb2.GetOperationRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_operation + + Override in a subclass to manipulate the request or metadata + before they are sent to the Adaptation server. + """ + return request, metadata + + def post_get_operation( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for get_operation + + Override in a subclass to manipulate the response + after it is returned by the Adaptation server but before + it is returned to user code. + """ + return response + + def pre_list_operations( + self, + request: operations_pb2.ListOperationsRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[operations_pb2.ListOperationsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_operations + + Override in a subclass to manipulate the request or metadata + before they are sent to the Adaptation server. + """ + return request, metadata + + def post_list_operations( + self, response: operations_pb2.ListOperationsResponse + ) -> operations_pb2.ListOperationsResponse: + """Post-rpc interceptor for list_operations + + Override in a subclass to manipulate the response + after it is returned by the Adaptation server but before + it is returned to user code. + """ + return response + + +@dataclasses.dataclass +class AdaptationRestStub: + _session: AuthorizedSession + _host: str + _interceptor: AdaptationRestInterceptor + + +class AdaptationRestTransport(AdaptationTransport): + """REST backend transport for Adaptation. + + Service that implements Google Cloud Speech Adaptation API. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends JSON representations of protocol buffers over HTTP/1.1 + + """ + + def __init__( + self, + *, + host: str = "speech.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + url_scheme: str = "https", + interceptor: Optional[AdaptationRestInterceptor] = None, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + client_cert_source_for_mtls (Callable[[], Tuple[bytes, bytes]]): Client + certificate to configure mutual TLS HTTP channel. It is ignored + if ``channel`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you are developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + url_scheme: the protocol scheme for the API endpoint. Normally + "https", but for testing or local servers, + "http" can be specified. + """ + # Run the base constructor + # TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc. + # TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the + # credentials object + maybe_url_match = re.match("^(?Phttp(?:s)?://)?(?P.*)$", host) + if maybe_url_match is None: + raise ValueError( + f"Unexpected hostname structure: {host}" + ) # pragma: NO COVER + + url_match_items = maybe_url_match.groupdict() + + host = f"{url_scheme}://{host}" if not url_match_items["scheme"] else host + + super().__init__( + host=host, + credentials=credentials, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + self._session = AuthorizedSession( + self._credentials, default_host=self.DEFAULT_HOST + ) + if client_cert_source_for_mtls: + self._session.configure_mtls_channel(client_cert_source_for_mtls) + self._interceptor = interceptor or AdaptationRestInterceptor() + self._prep_wrapped_messages(client_info) + + class _CreateCustomClass(AdaptationRestStub): + def __hash__(self): + return hash("CreateCustomClass") + + __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 + } + + def __call__( + self, + request: cloud_speech_adaptation.CreateCustomClassRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> resource.CustomClass: + r"""Call the create custom class method over HTTP. + + Args: + request (~.cloud_speech_adaptation.CreateCustomClassRequest): + The request object. Message sent by the client for the ``CreateCustomClass`` + method. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.resource.CustomClass: + A set of words or phrases that + represents a common concept likely to + appear in your audio, for example a list + of passenger ship names. CustomClass + items can be substituted into + placeholders that you set in PhraseSet + phrases. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1p1beta1/{parent=projects/*/locations/*}/customClasses", + "body": "*", + }, + ] + request, metadata = self._interceptor.pre_create_custom_class( + request, metadata + ) + pb_request = cloud_speech_adaptation.CreateCustomClassRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=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 = resource.CustomClass() + pb_resp = resource.CustomClass.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_create_custom_class(resp) + return resp + + class _CreatePhraseSet(AdaptationRestStub): + def __hash__(self): + return hash("CreatePhraseSet") + + __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 + } + + def __call__( + self, + request: cloud_speech_adaptation.CreatePhraseSetRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> resource.PhraseSet: + r"""Call the create phrase set method over HTTP. + + Args: + request (~.cloud_speech_adaptation.CreatePhraseSetRequest): + The request object. Message sent by the client for the ``CreatePhraseSet`` + method. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.resource.PhraseSet: + Provides "hints" to the speech + recognizer to favor specific words and + phrases in the results. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1p1beta1/{parent=projects/*/locations/*}/phraseSets", + "body": "*", + }, + ] + request, metadata = self._interceptor.pre_create_phrase_set( + request, metadata + ) + pb_request = cloud_speech_adaptation.CreatePhraseSetRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=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 = resource.PhraseSet() + pb_resp = resource.PhraseSet.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_create_phrase_set(resp) + return resp + + class _DeleteCustomClass(AdaptationRestStub): + def __hash__(self): + return hash("DeleteCustomClass") + + __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 + } + + def __call__( + self, + request: cloud_speech_adaptation.DeleteCustomClassRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ): + r"""Call the delete custom class method over HTTP. + + Args: + request (~.cloud_speech_adaptation.DeleteCustomClassRequest): + The request object. Message sent by the client for the ``DeleteCustomClass`` + method. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "delete", + "uri": "/v1p1beta1/{name=projects/*/locations/*/customClasses/*}", + }, + ] + request, metadata = self._interceptor.pre_delete_custom_class( + request, metadata + ) + pb_request = cloud_speech_adaptation.DeleteCustomClassRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + class _DeletePhraseSet(AdaptationRestStub): + def __hash__(self): + return hash("DeletePhraseSet") + + __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 + } + + def __call__( + self, + request: cloud_speech_adaptation.DeletePhraseSetRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ): + r"""Call the delete phrase set method over HTTP. + + Args: + request (~.cloud_speech_adaptation.DeletePhraseSetRequest): + The request object. Message sent by the client for the ``DeletePhraseSet`` + method. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "delete", + "uri": "/v1p1beta1/{name=projects/*/locations/*/phraseSets/*}", + }, + ] + request, metadata = self._interceptor.pre_delete_phrase_set( + request, metadata + ) + pb_request = cloud_speech_adaptation.DeletePhraseSetRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + class _GetCustomClass(AdaptationRestStub): + def __hash__(self): + return hash("GetCustomClass") + + __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 + } + + def __call__( + self, + request: cloud_speech_adaptation.GetCustomClassRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> resource.CustomClass: + r"""Call the get custom class method over HTTP. + + Args: + request (~.cloud_speech_adaptation.GetCustomClassRequest): + The request object. Message sent by the client for the ``GetCustomClass`` + method. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.resource.CustomClass: + A set of words or phrases that + represents a common concept likely to + appear in your audio, for example a list + of passenger ship names. CustomClass + items can be substituted into + placeholders that you set in PhraseSet + phrases. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1p1beta1/{name=projects/*/locations/*/customClasses/*}", + }, + ] + request, metadata = self._interceptor.pre_get_custom_class( + request, metadata + ) + pb_request = cloud_speech_adaptation.GetCustomClassRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # 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 = resource.CustomClass() + pb_resp = resource.CustomClass.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_custom_class(resp) + return resp + + class _GetPhraseSet(AdaptationRestStub): + def __hash__(self): + return hash("GetPhraseSet") + + __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 + } + + def __call__( + self, + request: cloud_speech_adaptation.GetPhraseSetRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> resource.PhraseSet: + r"""Call the get phrase set method over HTTP. + + Args: + request (~.cloud_speech_adaptation.GetPhraseSetRequest): + The request object. Message sent by the client for the ``GetPhraseSet`` + method. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.resource.PhraseSet: + Provides "hints" to the speech + recognizer to favor specific words and + phrases in the results. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1p1beta1/{name=projects/*/locations/*/phraseSets/*}", + }, + ] + request, metadata = self._interceptor.pre_get_phrase_set(request, metadata) + pb_request = cloud_speech_adaptation.GetPhraseSetRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # 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 = resource.PhraseSet() + pb_resp = resource.PhraseSet.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_phrase_set(resp) + return resp + + class _ListCustomClasses(AdaptationRestStub): + def __hash__(self): + return hash("ListCustomClasses") + + __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 + } + + def __call__( + self, + request: cloud_speech_adaptation.ListCustomClassesRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> cloud_speech_adaptation.ListCustomClassesResponse: + r"""Call the list custom classes method over HTTP. + + Args: + request (~.cloud_speech_adaptation.ListCustomClassesRequest): + The request object. Message sent by the client for the ``ListCustomClasses`` + method. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.cloud_speech_adaptation.ListCustomClassesResponse: + Message returned to the client by the + ``ListCustomClasses`` method. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1p1beta1/{parent=projects/*/locations/*}/customClasses", + }, + ] + request, metadata = self._interceptor.pre_list_custom_classes( + request, metadata + ) + pb_request = cloud_speech_adaptation.ListCustomClassesRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # 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 = cloud_speech_adaptation.ListCustomClassesResponse() + pb_resp = cloud_speech_adaptation.ListCustomClassesResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_custom_classes(resp) + return resp + + class _ListPhraseSet(AdaptationRestStub): + def __hash__(self): + return hash("ListPhraseSet") + + __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 + } + + def __call__( + self, + request: cloud_speech_adaptation.ListPhraseSetRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> cloud_speech_adaptation.ListPhraseSetResponse: + r"""Call the list phrase set method over HTTP. + + Args: + request (~.cloud_speech_adaptation.ListPhraseSetRequest): + The request object. Message sent by the client for the ``ListPhraseSet`` + method. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.cloud_speech_adaptation.ListPhraseSetResponse: + Message returned to the client by the ``ListPhraseSet`` + method. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1p1beta1/{parent=projects/*/locations/*}/phraseSets", + }, + ] + request, metadata = self._interceptor.pre_list_phrase_set(request, metadata) + pb_request = cloud_speech_adaptation.ListPhraseSetRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # 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 = cloud_speech_adaptation.ListPhraseSetResponse() + pb_resp = cloud_speech_adaptation.ListPhraseSetResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_phrase_set(resp) + return resp + + class _UpdateCustomClass(AdaptationRestStub): + def __hash__(self): + return hash("UpdateCustomClass") + + __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 + } + + def __call__( + self, + request: cloud_speech_adaptation.UpdateCustomClassRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> resource.CustomClass: + r"""Call the update custom class method over HTTP. + + Args: + request (~.cloud_speech_adaptation.UpdateCustomClassRequest): + The request object. Message sent by the client for the ``UpdateCustomClass`` + method. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.resource.CustomClass: + A set of words or phrases that + represents a common concept likely to + appear in your audio, for example a list + of passenger ship names. CustomClass + items can be substituted into + placeholders that you set in PhraseSet + phrases. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "patch", + "uri": "/v1p1beta1/{custom_class.name=projects/*/locations/*/customClasses/*}", + "body": "custom_class", + }, + ] + request, metadata = self._interceptor.pre_update_custom_class( + request, metadata + ) + pb_request = cloud_speech_adaptation.UpdateCustomClassRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=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 = resource.CustomClass() + pb_resp = resource.CustomClass.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_update_custom_class(resp) + return resp + + class _UpdatePhraseSet(AdaptationRestStub): + def __hash__(self): + return hash("UpdatePhraseSet") + + __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 + } + + def __call__( + self, + request: cloud_speech_adaptation.UpdatePhraseSetRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> resource.PhraseSet: + r"""Call the update phrase set method over HTTP. + + Args: + request (~.cloud_speech_adaptation.UpdatePhraseSetRequest): + The request object. Message sent by the client for the ``UpdatePhraseSet`` + method. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.resource.PhraseSet: + Provides "hints" to the speech + recognizer to favor specific words and + phrases in the results. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "patch", + "uri": "/v1p1beta1/{phrase_set.name=projects/*/locations/*/phraseSets/*}", + "body": "phrase_set", + }, + ] + request, metadata = self._interceptor.pre_update_phrase_set( + request, metadata + ) + pb_request = cloud_speech_adaptation.UpdatePhraseSetRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=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 = resource.PhraseSet() + pb_resp = resource.PhraseSet.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_update_phrase_set(resp) + return resp + + @property + def create_custom_class( + self, + ) -> Callable[ + [cloud_speech_adaptation.CreateCustomClassRequest], resource.CustomClass + ]: + # 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._CreateCustomClass(self._session, self._host, self._interceptor) # type: ignore + + @property + def create_phrase_set( + self, + ) -> Callable[[cloud_speech_adaptation.CreatePhraseSetRequest], resource.PhraseSet]: + # 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._CreatePhraseSet(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_custom_class( + self, + ) -> Callable[[cloud_speech_adaptation.DeleteCustomClassRequest], empty_pb2.Empty]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._DeleteCustomClass(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_phrase_set( + self, + ) -> Callable[[cloud_speech_adaptation.DeletePhraseSetRequest], empty_pb2.Empty]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._DeletePhraseSet(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_custom_class( + self, + ) -> Callable[ + [cloud_speech_adaptation.GetCustomClassRequest], resource.CustomClass + ]: + # 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._GetCustomClass(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_phrase_set( + self, + ) -> Callable[[cloud_speech_adaptation.GetPhraseSetRequest], resource.PhraseSet]: + # 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._GetPhraseSet(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_custom_classes( + self, + ) -> Callable[ + [cloud_speech_adaptation.ListCustomClassesRequest], + cloud_speech_adaptation.ListCustomClassesResponse, + ]: + # 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._ListCustomClasses(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_phrase_set( + self, + ) -> Callable[ + [cloud_speech_adaptation.ListPhraseSetRequest], + cloud_speech_adaptation.ListPhraseSetResponse, + ]: + # 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._ListPhraseSet(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_custom_class( + self, + ) -> Callable[ + [cloud_speech_adaptation.UpdateCustomClassRequest], resource.CustomClass + ]: + # 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._UpdateCustomClass(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_phrase_set( + self, + ) -> Callable[[cloud_speech_adaptation.UpdatePhraseSetRequest], resource.PhraseSet]: + # 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._UpdatePhraseSet(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_operation(self): + return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore + + class _GetOperation(AdaptationRestStub): + def __call__( + self, + request: operations_pb2.GetOperationRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + + r"""Call the get operation method over HTTP. + + Args: + request (operations_pb2.GetOperationRequest): + The request object for GetOperation method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + operations_pb2.Operation: Response from GetOperation method. + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1p1beta1/operations/{name=**}", + }, + ] + + request, metadata = self._interceptor.pre_get_operation(request, metadata) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + resp = operations_pb2.Operation() + resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = self._interceptor.post_get_operation(resp) + return resp + + @property + def list_operations(self): + return self._ListOperations(self._session, self._host, self._interceptor) # type: ignore + + class _ListOperations(AdaptationRestStub): + def __call__( + self, + request: operations_pb2.ListOperationsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.ListOperationsResponse: + + r"""Call the list operations method over HTTP. + + Args: + request (operations_pb2.ListOperationsRequest): + The request object for ListOperations method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + operations_pb2.ListOperationsResponse: Response from ListOperations method. + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1p1beta1/operations", + }, + ] + + request, metadata = self._interceptor.pre_list_operations(request, metadata) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + resp = operations_pb2.ListOperationsResponse() + resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = self._interceptor.post_list_operations(resp) + return resp + + @property + def kind(self) -> str: + return "rest" + + def close(self): + self._session.close() + + +__all__ = ("AdaptationRestTransport",) diff --git a/google/cloud/speech_v1p1beta1/services/speech/async_client.py b/google/cloud/speech_v1p1beta1/services/speech/async_client.py index 68578476..f4db3b5a 100644 --- a/google/cloud/speech_v1p1beta1/services/speech/async_client.py +++ b/google/cloud/speech_v1p1beta1/services/speech/async_client.py @@ -48,6 +48,7 @@ from google.api_core import operation # type: ignore from google.api_core import operation_async # type: ignore from google.cloud.speech_v1p1beta1.types import cloud_speech +from google.longrunning import operations_pb2 from google.protobuf import duration_pb2 # type: ignore from google.rpc import status_pb2 # type: ignore from .transports.base import SpeechTransport, DEFAULT_CLIENT_INFO @@ -637,6 +638,114 @@ def request_generator(): # Done; return the response. return response + async def list_operations( + self, + request: Optional[operations_pb2.ListOperationsRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.ListOperationsResponse: + r"""Lists operations that match the specified filter in the request. + + Args: + request (:class:`~.operations_pb2.ListOperationsRequest`): + The request object. Request message for + `ListOperations` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.operations_pb2.ListOperationsResponse: + Response message for ``ListOperations`` method. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.ListOperationsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._client._transport.list_operations, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # 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),)), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_operation( + self, + request: Optional[operations_pb2.GetOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + r"""Gets the latest state of a long-running operation. + + Args: + request (:class:`~.operations_pb2.GetOperationRequest`): + The request object. Request message for + `GetOperation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.operations_pb2.Operation: + An ``Operation`` object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.GetOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._client._transport.get_operation, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # 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),)), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + async def __aenter__(self): return self diff --git a/google/cloud/speech_v1p1beta1/services/speech/client.py b/google/cloud/speech_v1p1beta1/services/speech/client.py index e5d1b463..c8cf6f10 100644 --- a/google/cloud/speech_v1p1beta1/services/speech/client.py +++ b/google/cloud/speech_v1p1beta1/services/speech/client.py @@ -51,11 +51,13 @@ from google.api_core import operation # type: ignore from google.api_core import operation_async # type: ignore from google.cloud.speech_v1p1beta1.types import cloud_speech +from google.longrunning import operations_pb2 from google.protobuf import duration_pb2 # type: ignore from google.rpc import status_pb2 # type: ignore from .transports.base import SpeechTransport, DEFAULT_CLIENT_INFO from .transports.grpc import SpeechGrpcTransport from .transports.grpc_asyncio import SpeechGrpcAsyncIOTransport +from .transports.rest import SpeechRestTransport class SpeechClientMeta(type): @@ -69,6 +71,7 @@ class SpeechClientMeta(type): _transport_registry = OrderedDict() # type: Dict[str, Type[SpeechTransport]] _transport_registry["grpc"] = SpeechGrpcTransport _transport_registry["grpc_asyncio"] = SpeechGrpcAsyncIOTransport + _transport_registry["rest"] = SpeechRestTransport def get_transport_class( cls, @@ -878,6 +881,114 @@ def __exit__(self, type, value, traceback): """ self.transport.close() + def list_operations( + self, + request: Optional[operations_pb2.ListOperationsRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.ListOperationsResponse: + r"""Lists operations that match the specified filter in the request. + + Args: + request (:class:`~.operations_pb2.ListOperationsRequest`): + The request object. Request message for + `ListOperations` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.operations_pb2.ListOperationsResponse: + Response message for ``ListOperations`` method. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.ListOperationsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.list_operations, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # 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),)), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_operation( + self, + request: Optional[operations_pb2.GetOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + r"""Gets the latest state of a long-running operation. + + Args: + request (:class:`~.operations_pb2.GetOperationRequest`): + The request object. Request message for + `GetOperation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.operations_pb2.Operation: + An ``Operation`` object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.GetOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.get_operation, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # 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),)), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( gapic_version=package_version.__version__ diff --git a/google/cloud/speech_v1p1beta1/services/speech/transports/__init__.py b/google/cloud/speech_v1p1beta1/services/speech/transports/__init__.py index 4f7834ee..ce902d84 100644 --- a/google/cloud/speech_v1p1beta1/services/speech/transports/__init__.py +++ b/google/cloud/speech_v1p1beta1/services/speech/transports/__init__.py @@ -19,15 +19,20 @@ from .base import SpeechTransport from .grpc import SpeechGrpcTransport from .grpc_asyncio import SpeechGrpcAsyncIOTransport +from .rest import SpeechRestTransport +from .rest import SpeechRestInterceptor # Compile a registry of transports. _transport_registry = OrderedDict() # type: Dict[str, Type[SpeechTransport]] _transport_registry["grpc"] = SpeechGrpcTransport _transport_registry["grpc_asyncio"] = SpeechGrpcAsyncIOTransport +_transport_registry["rest"] = SpeechRestTransport __all__ = ( "SpeechTransport", "SpeechGrpcTransport", "SpeechGrpcAsyncIOTransport", + "SpeechRestTransport", + "SpeechRestInterceptor", ) diff --git a/google/cloud/speech_v1p1beta1/services/speech/transports/base.py b/google/cloud/speech_v1p1beta1/services/speech/transports/base.py index 346b3aee..72fa46c7 100644 --- a/google/cloud/speech_v1p1beta1/services/speech/transports/base.py +++ b/google/cloud/speech_v1p1beta1/services/speech/transports/base.py @@ -28,6 +28,7 @@ from google.oauth2 import service_account # type: ignore from google.cloud.speech_v1p1beta1.types import cloud_speech +from google.longrunning import operations_pb2 from google.longrunning import operations_pb2 # type: ignore DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( @@ -208,6 +209,27 @@ def streaming_recognize( ]: raise NotImplementedError() + @property + def list_operations( + self, + ) -> Callable[ + [operations_pb2.ListOperationsRequest], + Union[ + operations_pb2.ListOperationsResponse, + Awaitable[operations_pb2.ListOperationsResponse], + ], + ]: + raise NotImplementedError() + + @property + def get_operation( + self, + ) -> Callable[ + [operations_pb2.GetOperationRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + @property def kind(self) -> str: raise NotImplementedError() diff --git a/google/cloud/speech_v1p1beta1/services/speech/transports/grpc.py b/google/cloud/speech_v1p1beta1/services/speech/transports/grpc.py index 58cdff42..6c74a4a4 100644 --- a/google/cloud/speech_v1p1beta1/services/speech/transports/grpc.py +++ b/google/cloud/speech_v1p1beta1/services/speech/transports/grpc.py @@ -26,6 +26,7 @@ import grpc # type: ignore from google.cloud.speech_v1p1beta1.types import cloud_speech +from google.longrunning import operations_pb2 from google.longrunning import operations_pb2 # type: ignore from .base import SpeechTransport, DEFAULT_CLIENT_INFO @@ -338,6 +339,42 @@ def streaming_recognize( def close(self): self.grpc_channel.close() + @property + def get_operation( + self, + ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: + r"""Return a callable for the get_operation method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_operation" not in self._stubs: + self._stubs["get_operation"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/GetOperation", + request_serializer=operations_pb2.GetOperationRequest.SerializeToString, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["get_operation"] + + @property + def list_operations( + self, + ) -> Callable[ + [operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse + ]: + r"""Return a callable for the list_operations method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_operations" not in self._stubs: + self._stubs["list_operations"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/ListOperations", + request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, + response_deserializer=operations_pb2.ListOperationsResponse.FromString, + ) + return self._stubs["list_operations"] + @property def kind(self) -> str: return "grpc" diff --git a/google/cloud/speech_v1p1beta1/services/speech/transports/grpc_asyncio.py b/google/cloud/speech_v1p1beta1/services/speech/transports/grpc_asyncio.py index e1cf92fe..5bc8be0a 100644 --- a/google/cloud/speech_v1p1beta1/services/speech/transports/grpc_asyncio.py +++ b/google/cloud/speech_v1p1beta1/services/speech/transports/grpc_asyncio.py @@ -26,6 +26,7 @@ from grpc.experimental import aio # type: ignore from google.cloud.speech_v1p1beta1.types import cloud_speech +from google.longrunning import operations_pb2 from google.longrunning import operations_pb2 # type: ignore from .base import SpeechTransport, DEFAULT_CLIENT_INFO from .grpc import SpeechGrpcTransport @@ -347,5 +348,41 @@ def streaming_recognize( def close(self): return self.grpc_channel.close() + @property + def get_operation( + self, + ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: + r"""Return a callable for the get_operation method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_operation" not in self._stubs: + self._stubs["get_operation"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/GetOperation", + request_serializer=operations_pb2.GetOperationRequest.SerializeToString, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["get_operation"] + + @property + def list_operations( + self, + ) -> Callable[ + [operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse + ]: + r"""Return a callable for the list_operations method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_operations" not in self._stubs: + self._stubs["list_operations"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/ListOperations", + request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, + response_deserializer=operations_pb2.ListOperationsResponse.FromString, + ) + return self._stubs["list_operations"] + __all__ = ("SpeechGrpcAsyncIOTransport",) diff --git a/google/cloud/speech_v1p1beta1/services/speech/transports/rest.py b/google/cloud/speech_v1p1beta1/services/speech/transports/rest.py new file mode 100644 index 00000000..0982ed28 --- /dev/null +++ b/google/cloud/speech_v1p1beta1/services/speech/transports/rest.py @@ -0,0 +1,709 @@ +# -*- coding: utf-8 -*- +# 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. +# + +from google.auth.transport.requests import AuthorizedSession # type: ignore +import json # type: ignore +import grpc # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.api_core import exceptions as core_exceptions +from google.api_core import retry as retries +from google.api_core import rest_helpers +from google.api_core import rest_streaming +from google.api_core import path_template +from google.api_core import gapic_v1 + +from google.protobuf import json_format +from google.api_core import operations_v1 +from google.longrunning import operations_pb2 +from requests import __version__ as requests_version +import dataclasses +import re +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union +import warnings + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + + +from google.cloud.speech_v1p1beta1.types import cloud_speech +from google.longrunning import operations_pb2 # type: ignore + +from .base import SpeechTransport, DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, + grpc_version=None, + rest_version=requests_version, +) + + +class SpeechRestInterceptor: + """Interceptor for Speech. + + Interceptors are used to manipulate requests, request metadata, and responses + in arbitrary ways. + Example use cases include: + * Logging + * Verifying requests according to service or custom semantics + * Stripping extraneous information from responses + + These use cases and more can be enabled by injecting an + instance of a custom subclass when constructing the SpeechRestTransport. + + .. code-block:: python + class MyCustomSpeechInterceptor(SpeechRestInterceptor): + def pre_long_running_recognize(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_long_running_recognize(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_recognize(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_recognize(self, response): + logging.log(f"Received response: {response}") + return response + + transport = SpeechRestTransport(interceptor=MyCustomSpeechInterceptor()) + client = SpeechClient(transport=transport) + + + """ + + def pre_long_running_recognize( + self, + request: cloud_speech.LongRunningRecognizeRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[cloud_speech.LongRunningRecognizeRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for long_running_recognize + + Override in a subclass to manipulate the request or metadata + before they are sent to the Speech server. + """ + return request, metadata + + def post_long_running_recognize( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for long_running_recognize + + Override in a subclass to manipulate the response + after it is returned by the Speech server but before + it is returned to user code. + """ + return response + + def pre_recognize( + self, + request: cloud_speech.RecognizeRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[cloud_speech.RecognizeRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for recognize + + Override in a subclass to manipulate the request or metadata + before they are sent to the Speech server. + """ + return request, metadata + + def post_recognize( + self, response: cloud_speech.RecognizeResponse + ) -> cloud_speech.RecognizeResponse: + """Post-rpc interceptor for recognize + + Override in a subclass to manipulate the response + after it is returned by the Speech server but before + it is returned to user code. + """ + return response + + def pre_get_operation( + self, + request: operations_pb2.GetOperationRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[operations_pb2.GetOperationRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_operation + + Override in a subclass to manipulate the request or metadata + before they are sent to the Speech server. + """ + return request, metadata + + def post_get_operation( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for get_operation + + Override in a subclass to manipulate the response + after it is returned by the Speech server but before + it is returned to user code. + """ + return response + + def pre_list_operations( + self, + request: operations_pb2.ListOperationsRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[operations_pb2.ListOperationsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_operations + + Override in a subclass to manipulate the request or metadata + before they are sent to the Speech server. + """ + return request, metadata + + def post_list_operations( + self, response: operations_pb2.ListOperationsResponse + ) -> operations_pb2.ListOperationsResponse: + """Post-rpc interceptor for list_operations + + Override in a subclass to manipulate the response + after it is returned by the Speech server but before + it is returned to user code. + """ + return response + + +@dataclasses.dataclass +class SpeechRestStub: + _session: AuthorizedSession + _host: str + _interceptor: SpeechRestInterceptor + + +class SpeechRestTransport(SpeechTransport): + """REST backend transport for Speech. + + Service that implements Google Cloud Speech API. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends JSON representations of protocol buffers over HTTP/1.1 + + """ + + def __init__( + self, + *, + host: str = "speech.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + url_scheme: str = "https", + interceptor: Optional[SpeechRestInterceptor] = None, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + client_cert_source_for_mtls (Callable[[], Tuple[bytes, bytes]]): Client + certificate to configure mutual TLS HTTP channel. It is ignored + if ``channel`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you are developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + url_scheme: the protocol scheme for the API endpoint. Normally + "https", but for testing or local servers, + "http" can be specified. + """ + # Run the base constructor + # TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc. + # TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the + # credentials object + maybe_url_match = re.match("^(?Phttp(?:s)?://)?(?P.*)$", host) + if maybe_url_match is None: + raise ValueError( + f"Unexpected hostname structure: {host}" + ) # pragma: NO COVER + + url_match_items = maybe_url_match.groupdict() + + host = f"{url_scheme}://{host}" if not url_match_items["scheme"] else host + + super().__init__( + host=host, + credentials=credentials, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + self._session = AuthorizedSession( + self._credentials, default_host=self.DEFAULT_HOST + ) + self._operations_client: Optional[operations_v1.AbstractOperationsClient] = None + if client_cert_source_for_mtls: + self._session.configure_mtls_channel(client_cert_source_for_mtls) + self._interceptor = interceptor or SpeechRestInterceptor() + self._prep_wrapped_messages(client_info) + + @property + def operations_client(self) -> operations_v1.AbstractOperationsClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Only create a new client if we do not already have one. + if self._operations_client is None: + http_options: Dict[str, List[Dict[str, str]]] = { + "google.longrunning.Operations.GetOperation": [ + { + "method": "get", + "uri": "/v1p1beta1/operations/{name=**}", + }, + ], + "google.longrunning.Operations.ListOperations": [ + { + "method": "get", + "uri": "/v1p1beta1/operations", + }, + ], + } + + rest_transport = operations_v1.OperationsRestTransport( + host=self._host, + # use the credentials which are saved + credentials=self._credentials, + scopes=self._scopes, + http_options=http_options, + path_prefix="v1p1beta1", + ) + + self._operations_client = operations_v1.AbstractOperationsClient( + transport=rest_transport + ) + + # Return the client from cache. + return self._operations_client + + class _LongRunningRecognize(SpeechRestStub): + def __hash__(self): + return hash("LongRunningRecognize") + + __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 + } + + def __call__( + self, + request: cloud_speech.LongRunningRecognizeRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + r"""Call the long running recognize method over HTTP. + + Args: + request (~.cloud_speech.LongRunningRecognizeRequest): + The request object. The top-level message sent by the client for the + ``LongRunningRecognize`` method. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1p1beta1/speech:longrunningrecognize", + "body": "*", + }, + ] + request, metadata = self._interceptor.pre_long_running_recognize( + request, metadata + ) + pb_request = cloud_speech.LongRunningRecognizeRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=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_long_running_recognize(resp) + return resp + + class _Recognize(SpeechRestStub): + def __hash__(self): + return hash("Recognize") + + __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 + } + + def __call__( + self, + request: cloud_speech.RecognizeRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> cloud_speech.RecognizeResponse: + r"""Call the recognize method over HTTP. + + Args: + request (~.cloud_speech.RecognizeRequest): + The request object. The top-level message sent by the client for the + ``Recognize`` method. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.cloud_speech.RecognizeResponse: + The only message returned to the client by the + ``Recognize`` method. It contains the result as zero or + more sequential ``SpeechRecognitionResult`` messages. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1p1beta1/speech:recognize", + "body": "*", + }, + ] + request, metadata = self._interceptor.pre_recognize(request, metadata) + pb_request = cloud_speech.RecognizeRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=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 = cloud_speech.RecognizeResponse() + pb_resp = cloud_speech.RecognizeResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_recognize(resp) + return resp + + class _StreamingRecognize(SpeechRestStub): + def __hash__(self): + return hash("StreamingRecognize") + + def __call__( + self, + request: cloud_speech.StreamingRecognizeRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> rest_streaming.ResponseIterator: + raise NotImplementedError( + "Method StreamingRecognize is not available over REST transport" + ) + + @property + def long_running_recognize( + self, + ) -> Callable[[cloud_speech.LongRunningRecognizeRequest], 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._LongRunningRecognize(self._session, self._host, self._interceptor) # type: ignore + + @property + def recognize( + self, + ) -> Callable[[cloud_speech.RecognizeRequest], cloud_speech.RecognizeResponse]: + # 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._Recognize(self._session, self._host, self._interceptor) # type: ignore + + @property + def streaming_recognize( + self, + ) -> Callable[ + [cloud_speech.StreamingRecognizeRequest], + cloud_speech.StreamingRecognizeResponse, + ]: + # 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._StreamingRecognize(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_operation(self): + return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore + + class _GetOperation(SpeechRestStub): + def __call__( + self, + request: operations_pb2.GetOperationRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + + r"""Call the get operation method over HTTP. + + Args: + request (operations_pb2.GetOperationRequest): + The request object for GetOperation method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + operations_pb2.Operation: Response from GetOperation method. + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1p1beta1/operations/{name=**}", + }, + ] + + request, metadata = self._interceptor.pre_get_operation(request, metadata) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + resp = operations_pb2.Operation() + resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = self._interceptor.post_get_operation(resp) + return resp + + @property + def list_operations(self): + return self._ListOperations(self._session, self._host, self._interceptor) # type: ignore + + class _ListOperations(SpeechRestStub): + def __call__( + self, + request: operations_pb2.ListOperationsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.ListOperationsResponse: + + r"""Call the list operations method over HTTP. + + Args: + request (operations_pb2.ListOperationsRequest): + The request object for ListOperations method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + operations_pb2.ListOperationsResponse: Response from ListOperations method. + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1p1beta1/operations", + }, + ] + + request, metadata = self._interceptor.pre_list_operations(request, metadata) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + resp = operations_pb2.ListOperationsResponse() + resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = self._interceptor.post_list_operations(resp) + return resp + + @property + def kind(self) -> str: + return "rest" + + def close(self): + self._session.close() + + +__all__ = ("SpeechRestTransport",) diff --git a/google/cloud/speech_v1p1beta1/types/cloud_speech.py b/google/cloud/speech_v1p1beta1/types/cloud_speech.py index 82cebcca..a5a6b499 100644 --- a/google/cloud/speech_v1p1beta1/types/cloud_speech.py +++ b/google/cloud/speech_v1p1beta1/types/cloud_speech.py @@ -13,6 +13,8 @@ # See the License for the specific language governing permissions and # limitations under the License. # +from __future__ import annotations + from typing import MutableMapping, MutableSequence import proto # type: ignore @@ -223,8 +225,39 @@ class StreamingRecognitionConfig(proto.Message): returned as they become available (these interim results are indicated with the ``is_final=false`` flag). If ``false`` or omitted, only ``is_final=true`` result(s) are returned. + enable_voice_activity_events (bool): + If ``true``, responses with voice activity speech events + will be returned as they are detected. + voice_activity_timeout (google.cloud.speech_v1p1beta1.types.StreamingRecognitionConfig.VoiceActivityTimeout): + If set, the server will automatically close the stream after + the specified duration has elapsed after the last + VOICE_ACTIVITY speech event has been sent. The field + ``voice_activity_events`` must also be set to true. """ + class VoiceActivityTimeout(proto.Message): + r"""Events that a timeout can be set on for voice activity. + + Attributes: + speech_start_timeout (google.protobuf.duration_pb2.Duration): + Duration to timeout the stream if no speech + begins. + speech_end_timeout (google.protobuf.duration_pb2.Duration): + Duration to timeout the stream after speech + ends. + """ + + speech_start_timeout: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=1, + message=duration_pb2.Duration, + ) + speech_end_timeout: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=2, + message=duration_pb2.Duration, + ) + config: "RecognitionConfig" = proto.Field( proto.MESSAGE, number=1, @@ -238,6 +271,15 @@ class StreamingRecognitionConfig(proto.Message): proto.BOOL, number=3, ) + enable_voice_activity_events: bool = proto.Field( + proto.BOOL, + number=5, + ) + voice_activity_timeout: VoiceActivityTimeout = proto.Field( + proto.MESSAGE, + number=6, + message=VoiceActivityTimeout, + ) class RecognitionConfig(proto.Message): @@ -1200,6 +1242,9 @@ class StreamingRecognizeResponse(proto.Message): ``is_final=false`` results (the interim results). speech_event_type (google.cloud.speech_v1p1beta1.types.StreamingRecognizeResponse.SpeechEventType): Indicates the type of speech event. + speech_event_time (google.protobuf.duration_pb2.Duration): + Time offset between the beginning of the + audio and event emission. total_billed_time (google.protobuf.duration_pb2.Duration): When available, billed audio seconds for the stream. Set only if this is the last response in @@ -1228,9 +1273,30 @@ class SpeechEventType(proto.Enum): additional results until the server closes the gRPC connection. This event is only sent if ``single_utterance`` was set to ``true``, and is not used otherwise. + SPEECH_ACTIVITY_BEGIN (2): + This event indicates that the server has detected the + beginning of human voice activity in the stream. This event + can be returned multiple times if speech starts and stops + repeatedly throughout the stream. This event is only sent if + ``voice_activity_events`` is set to true. + SPEECH_ACTIVITY_END (3): + This event indicates that the server has detected the end of + human voice activity in the stream. This event can be + returned multiple times if speech starts and stops + repeatedly throughout the stream. This event is only sent if + ``voice_activity_events`` is set to true. + SPEECH_ACTIVITY_TIMEOUT (4): + This event indicates that the user-set + timeout for speech activity begin or end has + exceeded. Upon receiving this event, the client + is expected to send a half close. Further audio + will not be processed. """ SPEECH_EVENT_UNSPECIFIED = 0 END_OF_SINGLE_UTTERANCE = 1 + SPEECH_ACTIVITY_BEGIN = 2 + SPEECH_ACTIVITY_END = 3 + SPEECH_ACTIVITY_TIMEOUT = 4 error: status_pb2.Status = proto.Field( proto.MESSAGE, @@ -1247,6 +1313,11 @@ class SpeechEventType(proto.Enum): number=4, enum=SpeechEventType, ) + speech_event_time: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=8, + message=duration_pb2.Duration, + ) total_billed_time: duration_pb2.Duration = proto.Field( proto.MESSAGE, number=5, diff --git a/google/cloud/speech_v1p1beta1/types/cloud_speech_adaptation.py b/google/cloud/speech_v1p1beta1/types/cloud_speech_adaptation.py index 5931a9b9..5b12aae3 100644 --- a/google/cloud/speech_v1p1beta1/types/cloud_speech_adaptation.py +++ b/google/cloud/speech_v1p1beta1/types/cloud_speech_adaptation.py @@ -13,6 +13,8 @@ # See the License for the specific language governing permissions and # limitations under the License. # +from __future__ import annotations + from typing import MutableMapping, MutableSequence import proto # type: ignore diff --git a/google/cloud/speech_v1p1beta1/types/resource.py b/google/cloud/speech_v1p1beta1/types/resource.py index 6d438d55..eb104e9f 100644 --- a/google/cloud/speech_v1p1beta1/types/resource.py +++ b/google/cloud/speech_v1p1beta1/types/resource.py @@ -13,6 +13,8 @@ # See the License for the specific language governing permissions and # limitations under the License. # +from __future__ import annotations + from typing import MutableMapping, MutableSequence import proto # type: ignore diff --git a/google/cloud/speech_v2/gapic_metadata.json b/google/cloud/speech_v2/gapic_metadata.json index cfce8127..d835882c 100644 --- a/google/cloud/speech_v2/gapic_metadata.json +++ b/google/cloud/speech_v2/gapic_metadata.json @@ -246,6 +246,126 @@ ] } } + }, + "rest": { + "libraryClient": "SpeechClient", + "rpcs": { + "BatchRecognize": { + "methods": [ + "batch_recognize" + ] + }, + "CreateCustomClass": { + "methods": [ + "create_custom_class" + ] + }, + "CreatePhraseSet": { + "methods": [ + "create_phrase_set" + ] + }, + "CreateRecognizer": { + "methods": [ + "create_recognizer" + ] + }, + "DeleteCustomClass": { + "methods": [ + "delete_custom_class" + ] + }, + "DeletePhraseSet": { + "methods": [ + "delete_phrase_set" + ] + }, + "DeleteRecognizer": { + "methods": [ + "delete_recognizer" + ] + }, + "GetConfig": { + "methods": [ + "get_config" + ] + }, + "GetCustomClass": { + "methods": [ + "get_custom_class" + ] + }, + "GetPhraseSet": { + "methods": [ + "get_phrase_set" + ] + }, + "GetRecognizer": { + "methods": [ + "get_recognizer" + ] + }, + "ListCustomClasses": { + "methods": [ + "list_custom_classes" + ] + }, + "ListPhraseSets": { + "methods": [ + "list_phrase_sets" + ] + }, + "ListRecognizers": { + "methods": [ + "list_recognizers" + ] + }, + "Recognize": { + "methods": [ + "recognize" + ] + }, + "StreamingRecognize": { + "methods": [ + "streaming_recognize" + ] + }, + "UndeleteCustomClass": { + "methods": [ + "undelete_custom_class" + ] + }, + "UndeletePhraseSet": { + "methods": [ + "undelete_phrase_set" + ] + }, + "UndeleteRecognizer": { + "methods": [ + "undelete_recognizer" + ] + }, + "UpdateConfig": { + "methods": [ + "update_config" + ] + }, + "UpdateCustomClass": { + "methods": [ + "update_custom_class" + ] + }, + "UpdatePhraseSet": { + "methods": [ + "update_phrase_set" + ] + }, + "UpdateRecognizer": { + "methods": [ + "update_recognizer" + ] + } + } } } } diff --git a/google/cloud/speech_v2/gapic_version.py b/google/cloud/speech_v2/gapic_version.py index 36f3d159..f09943f6 100644 --- a/google/cloud/speech_v2/gapic_version.py +++ b/google/cloud/speech_v2/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "2.17.3" # {x-release-please-version} +__version__ = "2.18.0" # {x-release-please-version} diff --git a/google/cloud/speech_v2/services/speech/client.py b/google/cloud/speech_v2/services/speech/client.py index afdab6da..f285e880 100644 --- a/google/cloud/speech_v2/services/speech/client.py +++ b/google/cloud/speech_v2/services/speech/client.py @@ -59,6 +59,7 @@ from .transports.base import SpeechTransport, DEFAULT_CLIENT_INFO from .transports.grpc import SpeechGrpcTransport from .transports.grpc_asyncio import SpeechGrpcAsyncIOTransport +from .transports.rest import SpeechRestTransport class SpeechClientMeta(type): @@ -72,6 +73,7 @@ class SpeechClientMeta(type): _transport_registry = OrderedDict() # type: Dict[str, Type[SpeechTransport]] _transport_registry["grpc"] = SpeechGrpcTransport _transport_registry["grpc_asyncio"] = SpeechGrpcAsyncIOTransport + _transport_registry["rest"] = SpeechRestTransport def get_transport_class( cls, diff --git a/google/cloud/speech_v2/services/speech/transports/__init__.py b/google/cloud/speech_v2/services/speech/transports/__init__.py index 4f7834ee..ce902d84 100644 --- a/google/cloud/speech_v2/services/speech/transports/__init__.py +++ b/google/cloud/speech_v2/services/speech/transports/__init__.py @@ -19,15 +19,20 @@ from .base import SpeechTransport from .grpc import SpeechGrpcTransport from .grpc_asyncio import SpeechGrpcAsyncIOTransport +from .rest import SpeechRestTransport +from .rest import SpeechRestInterceptor # Compile a registry of transports. _transport_registry = OrderedDict() # type: Dict[str, Type[SpeechTransport]] _transport_registry["grpc"] = SpeechGrpcTransport _transport_registry["grpc_asyncio"] = SpeechGrpcAsyncIOTransport +_transport_registry["rest"] = SpeechRestTransport __all__ = ( "SpeechTransport", "SpeechGrpcTransport", "SpeechGrpcAsyncIOTransport", + "SpeechRestTransport", + "SpeechRestInterceptor", ) diff --git a/google/cloud/speech_v2/services/speech/transports/rest.py b/google/cloud/speech_v2/services/speech/transports/rest.py new file mode 100644 index 00000000..42654048 --- /dev/null +++ b/google/cloud/speech_v2/services/speech/transports/rest.py @@ -0,0 +1,3623 @@ +# -*- coding: utf-8 -*- +# 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. +# + +from google.auth.transport.requests import AuthorizedSession # type: ignore +import json # type: ignore +import grpc # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.api_core import exceptions as core_exceptions +from google.api_core import retry as retries +from google.api_core import rest_helpers +from google.api_core import rest_streaming +from google.api_core import path_template +from google.api_core import gapic_v1 + +from google.protobuf import json_format +from google.api_core import operations_v1 +from google.longrunning import operations_pb2 +from requests import __version__ as requests_version +import dataclasses +import re +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union +import warnings + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + + +from google.cloud.speech_v2.types import cloud_speech +from google.longrunning import operations_pb2 # type: ignore + +from .base import SpeechTransport, DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, + grpc_version=None, + rest_version=requests_version, +) + + +class SpeechRestInterceptor: + """Interceptor for Speech. + + Interceptors are used to manipulate requests, request metadata, and responses + in arbitrary ways. + Example use cases include: + * Logging + * Verifying requests according to service or custom semantics + * Stripping extraneous information from responses + + These use cases and more can be enabled by injecting an + instance of a custom subclass when constructing the SpeechRestTransport. + + .. code-block:: python + class MyCustomSpeechInterceptor(SpeechRestInterceptor): + def pre_batch_recognize(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_batch_recognize(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_create_custom_class(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_custom_class(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_create_phrase_set(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_phrase_set(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_create_recognizer(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_recognizer(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_delete_custom_class(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_delete_custom_class(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_delete_phrase_set(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_delete_phrase_set(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_delete_recognizer(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_delete_recognizer(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_config(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_config(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_custom_class(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_custom_class(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_phrase_set(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_phrase_set(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_recognizer(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_recognizer(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_custom_classes(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_custom_classes(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_phrase_sets(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_phrase_sets(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_recognizers(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_recognizers(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_recognize(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_recognize(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_undelete_custom_class(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_undelete_custom_class(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_undelete_phrase_set(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_undelete_phrase_set(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_undelete_recognizer(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_undelete_recognizer(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_config(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_config(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_custom_class(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_custom_class(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_phrase_set(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_phrase_set(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_recognizer(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_recognizer(self, response): + logging.log(f"Received response: {response}") + return response + + transport = SpeechRestTransport(interceptor=MyCustomSpeechInterceptor()) + client = SpeechClient(transport=transport) + + + """ + + def pre_batch_recognize( + self, + request: cloud_speech.BatchRecognizeRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[cloud_speech.BatchRecognizeRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for batch_recognize + + Override in a subclass to manipulate the request or metadata + before they are sent to the Speech server. + """ + return request, metadata + + def post_batch_recognize( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for batch_recognize + + Override in a subclass to manipulate the response + after it is returned by the Speech server but before + it is returned to user code. + """ + return response + + def pre_create_custom_class( + self, + request: cloud_speech.CreateCustomClassRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[cloud_speech.CreateCustomClassRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for create_custom_class + + Override in a subclass to manipulate the request or metadata + before they are sent to the Speech server. + """ + return request, metadata + + def post_create_custom_class( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for create_custom_class + + Override in a subclass to manipulate the response + after it is returned by the Speech server but before + it is returned to user code. + """ + return response + + def pre_create_phrase_set( + self, + request: cloud_speech.CreatePhraseSetRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[cloud_speech.CreatePhraseSetRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for create_phrase_set + + Override in a subclass to manipulate the request or metadata + before they are sent to the Speech server. + """ + return request, metadata + + def post_create_phrase_set( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for create_phrase_set + + Override in a subclass to manipulate the response + after it is returned by the Speech server but before + it is returned to user code. + """ + return response + + def pre_create_recognizer( + self, + request: cloud_speech.CreateRecognizerRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[cloud_speech.CreateRecognizerRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for create_recognizer + + Override in a subclass to manipulate the request or metadata + before they are sent to the Speech server. + """ + return request, metadata + + def post_create_recognizer( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for create_recognizer + + Override in a subclass to manipulate the response + after it is returned by the Speech server but before + it is returned to user code. + """ + return response + + def pre_delete_custom_class( + self, + request: cloud_speech.DeleteCustomClassRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[cloud_speech.DeleteCustomClassRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for delete_custom_class + + Override in a subclass to manipulate the request or metadata + before they are sent to the Speech server. + """ + return request, metadata + + def post_delete_custom_class( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for delete_custom_class + + Override in a subclass to manipulate the response + after it is returned by the Speech server but before + it is returned to user code. + """ + return response + + def pre_delete_phrase_set( + self, + request: cloud_speech.DeletePhraseSetRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[cloud_speech.DeletePhraseSetRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for delete_phrase_set + + Override in a subclass to manipulate the request or metadata + before they are sent to the Speech server. + """ + return request, metadata + + def post_delete_phrase_set( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for delete_phrase_set + + Override in a subclass to manipulate the response + after it is returned by the Speech server but before + it is returned to user code. + """ + return response + + def pre_delete_recognizer( + self, + request: cloud_speech.DeleteRecognizerRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[cloud_speech.DeleteRecognizerRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for delete_recognizer + + Override in a subclass to manipulate the request or metadata + before they are sent to the Speech server. + """ + return request, metadata + + def post_delete_recognizer( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for delete_recognizer + + Override in a subclass to manipulate the response + after it is returned by the Speech server but before + it is returned to user code. + """ + return response + + def pre_get_config( + self, + request: cloud_speech.GetConfigRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[cloud_speech.GetConfigRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_config + + Override in a subclass to manipulate the request or metadata + before they are sent to the Speech server. + """ + return request, metadata + + def post_get_config(self, response: cloud_speech.Config) -> cloud_speech.Config: + """Post-rpc interceptor for get_config + + Override in a subclass to manipulate the response + after it is returned by the Speech server but before + it is returned to user code. + """ + return response + + def pre_get_custom_class( + self, + request: cloud_speech.GetCustomClassRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[cloud_speech.GetCustomClassRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_custom_class + + Override in a subclass to manipulate the request or metadata + before they are sent to the Speech server. + """ + return request, metadata + + def post_get_custom_class( + self, response: cloud_speech.CustomClass + ) -> cloud_speech.CustomClass: + """Post-rpc interceptor for get_custom_class + + Override in a subclass to manipulate the response + after it is returned by the Speech server but before + it is returned to user code. + """ + return response + + def pre_get_phrase_set( + self, + request: cloud_speech.GetPhraseSetRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[cloud_speech.GetPhraseSetRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_phrase_set + + Override in a subclass to manipulate the request or metadata + before they are sent to the Speech server. + """ + return request, metadata + + def post_get_phrase_set( + self, response: cloud_speech.PhraseSet + ) -> cloud_speech.PhraseSet: + """Post-rpc interceptor for get_phrase_set + + Override in a subclass to manipulate the response + after it is returned by the Speech server but before + it is returned to user code. + """ + return response + + def pre_get_recognizer( + self, + request: cloud_speech.GetRecognizerRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[cloud_speech.GetRecognizerRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_recognizer + + Override in a subclass to manipulate the request or metadata + before they are sent to the Speech server. + """ + return request, metadata + + def post_get_recognizer( + self, response: cloud_speech.Recognizer + ) -> cloud_speech.Recognizer: + """Post-rpc interceptor for get_recognizer + + Override in a subclass to manipulate the response + after it is returned by the Speech server but before + it is returned to user code. + """ + return response + + def pre_list_custom_classes( + self, + request: cloud_speech.ListCustomClassesRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[cloud_speech.ListCustomClassesRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_custom_classes + + Override in a subclass to manipulate the request or metadata + before they are sent to the Speech server. + """ + return request, metadata + + def post_list_custom_classes( + self, response: cloud_speech.ListCustomClassesResponse + ) -> cloud_speech.ListCustomClassesResponse: + """Post-rpc interceptor for list_custom_classes + + Override in a subclass to manipulate the response + after it is returned by the Speech server but before + it is returned to user code. + """ + return response + + def pre_list_phrase_sets( + self, + request: cloud_speech.ListPhraseSetsRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[cloud_speech.ListPhraseSetsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_phrase_sets + + Override in a subclass to manipulate the request or metadata + before they are sent to the Speech server. + """ + return request, metadata + + def post_list_phrase_sets( + self, response: cloud_speech.ListPhraseSetsResponse + ) -> cloud_speech.ListPhraseSetsResponse: + """Post-rpc interceptor for list_phrase_sets + + Override in a subclass to manipulate the response + after it is returned by the Speech server but before + it is returned to user code. + """ + return response + + def pre_list_recognizers( + self, + request: cloud_speech.ListRecognizersRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[cloud_speech.ListRecognizersRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_recognizers + + Override in a subclass to manipulate the request or metadata + before they are sent to the Speech server. + """ + return request, metadata + + def post_list_recognizers( + self, response: cloud_speech.ListRecognizersResponse + ) -> cloud_speech.ListRecognizersResponse: + """Post-rpc interceptor for list_recognizers + + Override in a subclass to manipulate the response + after it is returned by the Speech server but before + it is returned to user code. + """ + return response + + def pre_recognize( + self, + request: cloud_speech.RecognizeRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[cloud_speech.RecognizeRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for recognize + + Override in a subclass to manipulate the request or metadata + before they are sent to the Speech server. + """ + return request, metadata + + def post_recognize( + self, response: cloud_speech.RecognizeResponse + ) -> cloud_speech.RecognizeResponse: + """Post-rpc interceptor for recognize + + Override in a subclass to manipulate the response + after it is returned by the Speech server but before + it is returned to user code. + """ + return response + + def pre_undelete_custom_class( + self, + request: cloud_speech.UndeleteCustomClassRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[cloud_speech.UndeleteCustomClassRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for undelete_custom_class + + Override in a subclass to manipulate the request or metadata + before they are sent to the Speech server. + """ + return request, metadata + + def post_undelete_custom_class( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for undelete_custom_class + + Override in a subclass to manipulate the response + after it is returned by the Speech server but before + it is returned to user code. + """ + return response + + def pre_undelete_phrase_set( + self, + request: cloud_speech.UndeletePhraseSetRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[cloud_speech.UndeletePhraseSetRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for undelete_phrase_set + + Override in a subclass to manipulate the request or metadata + before they are sent to the Speech server. + """ + return request, metadata + + def post_undelete_phrase_set( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for undelete_phrase_set + + Override in a subclass to manipulate the response + after it is returned by the Speech server but before + it is returned to user code. + """ + return response + + def pre_undelete_recognizer( + self, + request: cloud_speech.UndeleteRecognizerRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[cloud_speech.UndeleteRecognizerRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for undelete_recognizer + + Override in a subclass to manipulate the request or metadata + before they are sent to the Speech server. + """ + return request, metadata + + def post_undelete_recognizer( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for undelete_recognizer + + Override in a subclass to manipulate the response + after it is returned by the Speech server but before + it is returned to user code. + """ + return response + + def pre_update_config( + self, + request: cloud_speech.UpdateConfigRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[cloud_speech.UpdateConfigRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for update_config + + Override in a subclass to manipulate the request or metadata + before they are sent to the Speech server. + """ + return request, metadata + + def post_update_config(self, response: cloud_speech.Config) -> cloud_speech.Config: + """Post-rpc interceptor for update_config + + Override in a subclass to manipulate the response + after it is returned by the Speech server but before + it is returned to user code. + """ + return response + + def pre_update_custom_class( + self, + request: cloud_speech.UpdateCustomClassRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[cloud_speech.UpdateCustomClassRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for update_custom_class + + Override in a subclass to manipulate the request or metadata + before they are sent to the Speech server. + """ + return request, metadata + + def post_update_custom_class( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for update_custom_class + + Override in a subclass to manipulate the response + after it is returned by the Speech server but before + it is returned to user code. + """ + return response + + def pre_update_phrase_set( + self, + request: cloud_speech.UpdatePhraseSetRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[cloud_speech.UpdatePhraseSetRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for update_phrase_set + + Override in a subclass to manipulate the request or metadata + before they are sent to the Speech server. + """ + return request, metadata + + def post_update_phrase_set( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for update_phrase_set + + Override in a subclass to manipulate the response + after it is returned by the Speech server but before + it is returned to user code. + """ + return response + + def pre_update_recognizer( + self, + request: cloud_speech.UpdateRecognizerRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[cloud_speech.UpdateRecognizerRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for update_recognizer + + Override in a subclass to manipulate the request or metadata + before they are sent to the Speech server. + """ + return request, metadata + + def post_update_recognizer( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for update_recognizer + + Override in a subclass to manipulate the response + after it is returned by the Speech server but before + it is returned to user code. + """ + return response + + def pre_cancel_operation( + self, + request: operations_pb2.CancelOperationRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[operations_pb2.CancelOperationRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for cancel_operation + + Override in a subclass to manipulate the request or metadata + before they are sent to the Speech server. + """ + return request, metadata + + def post_cancel_operation(self, response: None) -> None: + """Post-rpc interceptor for cancel_operation + + Override in a subclass to manipulate the response + after it is returned by the Speech server but before + it is returned to user code. + """ + return response + + def pre_delete_operation( + self, + request: operations_pb2.DeleteOperationRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[operations_pb2.DeleteOperationRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for delete_operation + + Override in a subclass to manipulate the request or metadata + before they are sent to the Speech server. + """ + return request, metadata + + def post_delete_operation(self, response: None) -> None: + """Post-rpc interceptor for delete_operation + + Override in a subclass to manipulate the response + after it is returned by the Speech server but before + it is returned to user code. + """ + return response + + def pre_get_operation( + self, + request: operations_pb2.GetOperationRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[operations_pb2.GetOperationRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_operation + + Override in a subclass to manipulate the request or metadata + before they are sent to the Speech server. + """ + return request, metadata + + def post_get_operation( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for get_operation + + Override in a subclass to manipulate the response + after it is returned by the Speech server but before + it is returned to user code. + """ + return response + + def pre_list_operations( + self, + request: operations_pb2.ListOperationsRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[operations_pb2.ListOperationsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_operations + + Override in a subclass to manipulate the request or metadata + before they are sent to the Speech server. + """ + return request, metadata + + def post_list_operations( + self, response: operations_pb2.ListOperationsResponse + ) -> operations_pb2.ListOperationsResponse: + """Post-rpc interceptor for list_operations + + Override in a subclass to manipulate the response + after it is returned by the Speech server but before + it is returned to user code. + """ + return response + + +@dataclasses.dataclass +class SpeechRestStub: + _session: AuthorizedSession + _host: str + _interceptor: SpeechRestInterceptor + + +class SpeechRestTransport(SpeechTransport): + """REST backend transport for Speech. + + Enables speech transcription and resource management. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends JSON representations of protocol buffers over HTTP/1.1 + + """ + + def __init__( + self, + *, + host: str = "speech.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + url_scheme: str = "https", + interceptor: Optional[SpeechRestInterceptor] = None, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + client_cert_source_for_mtls (Callable[[], Tuple[bytes, bytes]]): Client + certificate to configure mutual TLS HTTP channel. It is ignored + if ``channel`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you are developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + url_scheme: the protocol scheme for the API endpoint. Normally + "https", but for testing or local servers, + "http" can be specified. + """ + # Run the base constructor + # TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc. + # TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the + # credentials object + maybe_url_match = re.match("^(?Phttp(?:s)?://)?(?P.*)$", host) + if maybe_url_match is None: + raise ValueError( + f"Unexpected hostname structure: {host}" + ) # pragma: NO COVER + + url_match_items = maybe_url_match.groupdict() + + host = f"{url_scheme}://{host}" if not url_match_items["scheme"] else host + + super().__init__( + host=host, + credentials=credentials, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + self._session = AuthorizedSession( + self._credentials, default_host=self.DEFAULT_HOST + ) + self._operations_client: Optional[operations_v1.AbstractOperationsClient] = None + if client_cert_source_for_mtls: + self._session.configure_mtls_channel(client_cert_source_for_mtls) + self._interceptor = interceptor or SpeechRestInterceptor() + self._prep_wrapped_messages(client_info) + + @property + def operations_client(self) -> operations_v1.AbstractOperationsClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Only create a new client if we do not already have one. + if self._operations_client is None: + http_options: Dict[str, List[Dict[str, str]]] = { + "google.longrunning.Operations.CancelOperation": [ + { + "method": "post", + "uri": "/v2/{name=projects/*/locations/*/operations/*}:cancel", + "body": "*", + }, + ], + "google.longrunning.Operations.DeleteOperation": [ + { + "method": "delete", + "uri": "/v2/{name=projects/*/locations/*/operations/*}", + }, + ], + "google.longrunning.Operations.GetOperation": [ + { + "method": "get", + "uri": "/v2/{name=projects/*/locations/*/operations/*}", + }, + ], + "google.longrunning.Operations.ListOperations": [ + { + "method": "get", + "uri": "/v2/{name=projects/*/locations/*}/operations", + }, + ], + } + + rest_transport = operations_v1.OperationsRestTransport( + host=self._host, + # use the credentials which are saved + credentials=self._credentials, + scopes=self._scopes, + http_options=http_options, + path_prefix="v2", + ) + + self._operations_client = operations_v1.AbstractOperationsClient( + transport=rest_transport + ) + + # Return the client from cache. + return self._operations_client + + class _BatchRecognize(SpeechRestStub): + def __hash__(self): + return hash("BatchRecognize") + + __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 + } + + def __call__( + self, + request: cloud_speech.BatchRecognizeRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + r"""Call the batch recognize method over HTTP. + + Args: + request (~.cloud_speech.BatchRecognizeRequest): + The request object. Request message for the + [BatchRecognize][google.cloud.speech.v2.Speech.BatchRecognize] + method. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v2/{recognizer=projects/*/locations/*/recognizers/*}:batchRecognize", + "body": "*", + }, + ] + request, metadata = self._interceptor.pre_batch_recognize(request, metadata) + pb_request = cloud_speech.BatchRecognizeRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=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_batch_recognize(resp) + return resp + + class _CreateCustomClass(SpeechRestStub): + def __hash__(self): + return hash("CreateCustomClass") + + __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 + } + + def __call__( + self, + request: cloud_speech.CreateCustomClassRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + r"""Call the create custom class method over HTTP. + + Args: + request (~.cloud_speech.CreateCustomClassRequest): + The request object. Request message for the + [CreateCustomClass][google.cloud.speech.v2.Speech.CreateCustomClass] + method. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v2/{parent=projects/*/locations/*}/customClasses", + "body": "custom_class", + }, + ] + request, metadata = self._interceptor.pre_create_custom_class( + request, metadata + ) + pb_request = cloud_speech.CreateCustomClassRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_create_custom_class(resp) + return resp + + class _CreatePhraseSet(SpeechRestStub): + def __hash__(self): + return hash("CreatePhraseSet") + + __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 + } + + def __call__( + self, + request: cloud_speech.CreatePhraseSetRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + r"""Call the create phrase set method over HTTP. + + Args: + request (~.cloud_speech.CreatePhraseSetRequest): + The request object. Request message for the + [CreatePhraseSet][google.cloud.speech.v2.Speech.CreatePhraseSet] + method. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v2/{parent=projects/*/locations/*}/phraseSets", + "body": "phrase_set", + }, + ] + request, metadata = self._interceptor.pre_create_phrase_set( + request, metadata + ) + pb_request = cloud_speech.CreatePhraseSetRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_create_phrase_set(resp) + return resp + + class _CreateRecognizer(SpeechRestStub): + def __hash__(self): + return hash("CreateRecognizer") + + __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 + } + + def __call__( + self, + request: cloud_speech.CreateRecognizerRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + r"""Call the create recognizer method over HTTP. + + Args: + request (~.cloud_speech.CreateRecognizerRequest): + The request object. Request message for the + [CreateRecognizer][google.cloud.speech.v2.Speech.CreateRecognizer] + method. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v2/{parent=projects/*/locations/*}/recognizers", + "body": "recognizer", + }, + ] + request, metadata = self._interceptor.pre_create_recognizer( + request, metadata + ) + pb_request = cloud_speech.CreateRecognizerRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_create_recognizer(resp) + return resp + + class _DeleteCustomClass(SpeechRestStub): + def __hash__(self): + return hash("DeleteCustomClass") + + __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 + } + + def __call__( + self, + request: cloud_speech.DeleteCustomClassRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + r"""Call the delete custom class method over HTTP. + + Args: + request (~.cloud_speech.DeleteCustomClassRequest): + The request object. Request message for the + [DeleteCustomClass][google.cloud.speech.v2.Speech.DeleteCustomClass] + method. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "delete", + "uri": "/v2/{name=projects/*/locations/*/customClasses/*}", + }, + ] + request, metadata = self._interceptor.pre_delete_custom_class( + request, metadata + ) + pb_request = cloud_speech.DeleteCustomClassRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_delete_custom_class(resp) + return resp + + class _DeletePhraseSet(SpeechRestStub): + def __hash__(self): + return hash("DeletePhraseSet") + + __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 + } + + def __call__( + self, + request: cloud_speech.DeletePhraseSetRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + r"""Call the delete phrase set method over HTTP. + + Args: + request (~.cloud_speech.DeletePhraseSetRequest): + The request object. Request message for the + [DeletePhraseSet][google.cloud.speech.v2.Speech.DeletePhraseSet] + method. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "delete", + "uri": "/v2/{name=projects/*/locations/*/phraseSets/*}", + }, + ] + request, metadata = self._interceptor.pre_delete_phrase_set( + request, metadata + ) + pb_request = cloud_speech.DeletePhraseSetRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_delete_phrase_set(resp) + return resp + + class _DeleteRecognizer(SpeechRestStub): + def __hash__(self): + return hash("DeleteRecognizer") + + __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 + } + + def __call__( + self, + request: cloud_speech.DeleteRecognizerRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + r"""Call the delete recognizer method over HTTP. + + Args: + request (~.cloud_speech.DeleteRecognizerRequest): + The request object. Request message for the + [DeleteRecognizer][google.cloud.speech.v2.Speech.DeleteRecognizer] + method. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "delete", + "uri": "/v2/{name=projects/*/locations/*/recognizers/*}", + }, + ] + request, metadata = self._interceptor.pre_delete_recognizer( + request, metadata + ) + pb_request = cloud_speech.DeleteRecognizerRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_delete_recognizer(resp) + return resp + + class _GetConfig(SpeechRestStub): + def __hash__(self): + return hash("GetConfig") + + __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 + } + + def __call__( + self, + request: cloud_speech.GetConfigRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> cloud_speech.Config: + r"""Call the get config method over HTTP. + + Args: + request (~.cloud_speech.GetConfigRequest): + The request object. Request message for the + [GetConfig][google.cloud.speech.v2.Speech.GetConfig] + method. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.cloud_speech.Config: + Message representing the config for the Speech-to-Text + API. This includes an optional `KMS + key `__ + with which incoming data will be encrypted. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v2/{name=projects/*/locations/*/config}", + }, + ] + request, metadata = self._interceptor.pre_get_config(request, metadata) + pb_request = cloud_speech.GetConfigRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # 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 = cloud_speech.Config() + pb_resp = cloud_speech.Config.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_config(resp) + return resp + + class _GetCustomClass(SpeechRestStub): + def __hash__(self): + return hash("GetCustomClass") + + __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 + } + + def __call__( + self, + request: cloud_speech.GetCustomClassRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> cloud_speech.CustomClass: + r"""Call the get custom class method over HTTP. + + Args: + request (~.cloud_speech.GetCustomClassRequest): + The request object. Request message for the + [GetCustomClass][google.cloud.speech.v2.Speech.GetCustomClass] + method. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.cloud_speech.CustomClass: + CustomClass for biasing in speech + recognition. Used to define a set of + words or phrases that represents a + common concept or theme likely to appear + in your audio, for example a list of + passenger ship names. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v2/{name=projects/*/locations/*/customClasses/*}", + }, + ] + request, metadata = self._interceptor.pre_get_custom_class( + request, metadata + ) + pb_request = cloud_speech.GetCustomClassRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # 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 = cloud_speech.CustomClass() + pb_resp = cloud_speech.CustomClass.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_custom_class(resp) + return resp + + class _GetPhraseSet(SpeechRestStub): + def __hash__(self): + return hash("GetPhraseSet") + + __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 + } + + def __call__( + self, + request: cloud_speech.GetPhraseSetRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> cloud_speech.PhraseSet: + r"""Call the get phrase set method over HTTP. + + Args: + request (~.cloud_speech.GetPhraseSetRequest): + The request object. Request message for the + [GetPhraseSet][google.cloud.speech.v2.Speech.GetPhraseSet] + method. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.cloud_speech.PhraseSet: + PhraseSet for biasing in speech + recognition. A PhraseSet is used to + provide "hints" to the speech recognizer + to favor specific words and phrases in + the results. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v2/{name=projects/*/locations/*/phraseSets/*}", + }, + ] + request, metadata = self._interceptor.pre_get_phrase_set(request, metadata) + pb_request = cloud_speech.GetPhraseSetRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # 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 = cloud_speech.PhraseSet() + pb_resp = cloud_speech.PhraseSet.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_phrase_set(resp) + return resp + + class _GetRecognizer(SpeechRestStub): + def __hash__(self): + return hash("GetRecognizer") + + __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 + } + + def __call__( + self, + request: cloud_speech.GetRecognizerRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> cloud_speech.Recognizer: + r"""Call the get recognizer method over HTTP. + + Args: + request (~.cloud_speech.GetRecognizerRequest): + The request object. Request message for the + [GetRecognizer][google.cloud.speech.v2.Speech.GetRecognizer] + method. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.cloud_speech.Recognizer: + A Recognizer message. Stores + recognition configuration and metadata. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v2/{name=projects/*/locations/*/recognizers/*}", + }, + ] + request, metadata = self._interceptor.pre_get_recognizer(request, metadata) + pb_request = cloud_speech.GetRecognizerRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # 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 = cloud_speech.Recognizer() + pb_resp = cloud_speech.Recognizer.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_recognizer(resp) + return resp + + class _ListCustomClasses(SpeechRestStub): + def __hash__(self): + return hash("ListCustomClasses") + + __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 + } + + def __call__( + self, + request: cloud_speech.ListCustomClassesRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> cloud_speech.ListCustomClassesResponse: + r"""Call the list custom classes method over HTTP. + + Args: + request (~.cloud_speech.ListCustomClassesRequest): + The request object. Request message for the + [ListCustomClasses][google.cloud.speech.v2.Speech.ListCustomClasses] + method. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.cloud_speech.ListCustomClassesResponse: + Response message for the + [ListCustomClasses][google.cloud.speech.v2.Speech.ListCustomClasses] + method. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v2/{parent=projects/*/locations/*}/customClasses", + }, + ] + request, metadata = self._interceptor.pre_list_custom_classes( + request, metadata + ) + pb_request = cloud_speech.ListCustomClassesRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # 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 = cloud_speech.ListCustomClassesResponse() + pb_resp = cloud_speech.ListCustomClassesResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_custom_classes(resp) + return resp + + class _ListPhraseSets(SpeechRestStub): + def __hash__(self): + return hash("ListPhraseSets") + + __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 + } + + def __call__( + self, + request: cloud_speech.ListPhraseSetsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> cloud_speech.ListPhraseSetsResponse: + r"""Call the list phrase sets method over HTTP. + + Args: + request (~.cloud_speech.ListPhraseSetsRequest): + The request object. Request message for the + [ListPhraseSets][google.cloud.speech.v2.Speech.ListPhraseSets] + method. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.cloud_speech.ListPhraseSetsResponse: + Response message for the + [ListPhraseSets][google.cloud.speech.v2.Speech.ListPhraseSets] + method. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v2/{parent=projects/*/locations/*}/phraseSets", + }, + ] + request, metadata = self._interceptor.pre_list_phrase_sets( + request, metadata + ) + pb_request = cloud_speech.ListPhraseSetsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # 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 = cloud_speech.ListPhraseSetsResponse() + pb_resp = cloud_speech.ListPhraseSetsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_phrase_sets(resp) + return resp + + class _ListRecognizers(SpeechRestStub): + def __hash__(self): + return hash("ListRecognizers") + + __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 + } + + def __call__( + self, + request: cloud_speech.ListRecognizersRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> cloud_speech.ListRecognizersResponse: + r"""Call the list recognizers method over HTTP. + + Args: + request (~.cloud_speech.ListRecognizersRequest): + The request object. Request message for the + [ListRecognizers][google.cloud.speech.v2.Speech.ListRecognizers] + method. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.cloud_speech.ListRecognizersResponse: + Response message for the + [ListRecognizers][google.cloud.speech.v2.Speech.ListRecognizers] + method. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v2/{parent=projects/*/locations/*}/recognizers", + }, + ] + request, metadata = self._interceptor.pre_list_recognizers( + request, metadata + ) + pb_request = cloud_speech.ListRecognizersRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # 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 = cloud_speech.ListRecognizersResponse() + pb_resp = cloud_speech.ListRecognizersResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_recognizers(resp) + return resp + + class _Recognize(SpeechRestStub): + def __hash__(self): + return hash("Recognize") + + __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 + } + + def __call__( + self, + request: cloud_speech.RecognizeRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> cloud_speech.RecognizeResponse: + r"""Call the recognize method over HTTP. + + Args: + request (~.cloud_speech.RecognizeRequest): + The request object. Request message for the + [Recognize][google.cloud.speech.v2.Speech.Recognize] + method. Either ``content`` or ``uri`` must be supplied. + Supplying both or neither returns + [INVALID_ARGUMENT][google.rpc.Code.INVALID_ARGUMENT]. + See `content + limits `__. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.cloud_speech.RecognizeResponse: + Response message for the + [Recognize][google.cloud.speech.v2.Speech.Recognize] + method. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v2/{recognizer=projects/*/locations/*/recognizers/*}:recognize", + "body": "*", + }, + ] + request, metadata = self._interceptor.pre_recognize(request, metadata) + pb_request = cloud_speech.RecognizeRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=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 = cloud_speech.RecognizeResponse() + pb_resp = cloud_speech.RecognizeResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_recognize(resp) + return resp + + class _StreamingRecognize(SpeechRestStub): + def __hash__(self): + return hash("StreamingRecognize") + + def __call__( + self, + request: cloud_speech.StreamingRecognizeRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> rest_streaming.ResponseIterator: + raise NotImplementedError( + "Method StreamingRecognize is not available over REST transport" + ) + + class _UndeleteCustomClass(SpeechRestStub): + def __hash__(self): + return hash("UndeleteCustomClass") + + __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 + } + + def __call__( + self, + request: cloud_speech.UndeleteCustomClassRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + r"""Call the undelete custom class method over HTTP. + + Args: + request (~.cloud_speech.UndeleteCustomClassRequest): + The request object. Request message for the + [UndeleteCustomClass][google.cloud.speech.v2.Speech.UndeleteCustomClass] + method. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v2/{name=projects/*/locations/*/customClasses/*}:undelete", + "body": "*", + }, + ] + request, metadata = self._interceptor.pre_undelete_custom_class( + request, metadata + ) + pb_request = cloud_speech.UndeleteCustomClassRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=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_undelete_custom_class(resp) + return resp + + class _UndeletePhraseSet(SpeechRestStub): + def __hash__(self): + return hash("UndeletePhraseSet") + + __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 + } + + def __call__( + self, + request: cloud_speech.UndeletePhraseSetRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + r"""Call the undelete phrase set method over HTTP. + + Args: + request (~.cloud_speech.UndeletePhraseSetRequest): + The request object. Request message for the + [UndeletePhraseSet][google.cloud.speech.v2.Speech.UndeletePhraseSet] + method. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v2/{name=projects/*/locations/*/phraseSets/*}:undelete", + "body": "*", + }, + ] + request, metadata = self._interceptor.pre_undelete_phrase_set( + request, metadata + ) + pb_request = cloud_speech.UndeletePhraseSetRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=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_undelete_phrase_set(resp) + return resp + + class _UndeleteRecognizer(SpeechRestStub): + def __hash__(self): + return hash("UndeleteRecognizer") + + __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 + } + + def __call__( + self, + request: cloud_speech.UndeleteRecognizerRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + r"""Call the undelete recognizer method over HTTP. + + Args: + request (~.cloud_speech.UndeleteRecognizerRequest): + The request object. Request message for the + [UndeleteRecognizer][google.cloud.speech.v2.Speech.UndeleteRecognizer] + method. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v2/{name=projects/*/locations/*/recognizers/*}:undelete", + "body": "*", + }, + ] + request, metadata = self._interceptor.pre_undelete_recognizer( + request, metadata + ) + pb_request = cloud_speech.UndeleteRecognizerRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=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_undelete_recognizer(resp) + return resp + + class _UpdateConfig(SpeechRestStub): + def __hash__(self): + return hash("UpdateConfig") + + __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 + } + + def __call__( + self, + request: cloud_speech.UpdateConfigRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> cloud_speech.Config: + r"""Call the update config method over HTTP. + + Args: + request (~.cloud_speech.UpdateConfigRequest): + The request object. Request message for the + [UpdateConfig][google.cloud.speech.v2.Speech.UpdateConfig] + method. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.cloud_speech.Config: + Message representing the config for the Speech-to-Text + API. This includes an optional `KMS + key `__ + with which incoming data will be encrypted. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "patch", + "uri": "/v2/{config.name=projects/*/locations/*/config}", + "body": "config", + }, + ] + request, metadata = self._interceptor.pre_update_config(request, metadata) + pb_request = cloud_speech.UpdateConfigRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=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 = cloud_speech.Config() + pb_resp = cloud_speech.Config.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_update_config(resp) + return resp + + class _UpdateCustomClass(SpeechRestStub): + def __hash__(self): + return hash("UpdateCustomClass") + + __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 + } + + def __call__( + self, + request: cloud_speech.UpdateCustomClassRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + r"""Call the update custom class method over HTTP. + + Args: + request (~.cloud_speech.UpdateCustomClassRequest): + The request object. Request message for the + [UpdateCustomClass][google.cloud.speech.v2.Speech.UpdateCustomClass] + method. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "patch", + "uri": "/v2/{custom_class.name=projects/*/locations/*/customClasses/*}", + "body": "custom_class", + }, + ] + request, metadata = self._interceptor.pre_update_custom_class( + request, metadata + ) + pb_request = cloud_speech.UpdateCustomClassRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=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_custom_class(resp) + return resp + + class _UpdatePhraseSet(SpeechRestStub): + def __hash__(self): + return hash("UpdatePhraseSet") + + __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 + } + + def __call__( + self, + request: cloud_speech.UpdatePhraseSetRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + r"""Call the update phrase set method over HTTP. + + Args: + request (~.cloud_speech.UpdatePhraseSetRequest): + The request object. Request message for the + [UpdatePhraseSet][google.cloud.speech.v2.Speech.UpdatePhraseSet] + method. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "patch", + "uri": "/v2/{phrase_set.name=projects/*/locations/*/phraseSets/*}", + "body": "phrase_set", + }, + ] + request, metadata = self._interceptor.pre_update_phrase_set( + request, metadata + ) + pb_request = cloud_speech.UpdatePhraseSetRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=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_phrase_set(resp) + return resp + + class _UpdateRecognizer(SpeechRestStub): + def __hash__(self): + return hash("UpdateRecognizer") + + __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 + } + + def __call__( + self, + request: cloud_speech.UpdateRecognizerRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + r"""Call the update recognizer method over HTTP. + + Args: + request (~.cloud_speech.UpdateRecognizerRequest): + The request object. Request message for the + [UpdateRecognizer][google.cloud.speech.v2.Speech.UpdateRecognizer] + method. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "patch", + "uri": "/v2/{recognizer.name=projects/*/locations/*/recognizers/*}", + "body": "recognizer", + }, + ] + request, metadata = self._interceptor.pre_update_recognizer( + request, metadata + ) + pb_request = cloud_speech.UpdateRecognizerRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=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_recognizer(resp) + return resp + + @property + def batch_recognize( + self, + ) -> Callable[[cloud_speech.BatchRecognizeRequest], 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._BatchRecognize(self._session, self._host, self._interceptor) # type: ignore + + @property + def create_custom_class( + self, + ) -> Callable[[cloud_speech.CreateCustomClassRequest], 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._CreateCustomClass(self._session, self._host, self._interceptor) # type: ignore + + @property + def create_phrase_set( + self, + ) -> Callable[[cloud_speech.CreatePhraseSetRequest], 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._CreatePhraseSet(self._session, self._host, self._interceptor) # type: ignore + + @property + def create_recognizer( + self, + ) -> Callable[[cloud_speech.CreateRecognizerRequest], 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._CreateRecognizer(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_custom_class( + self, + ) -> Callable[[cloud_speech.DeleteCustomClassRequest], 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._DeleteCustomClass(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_phrase_set( + self, + ) -> Callable[[cloud_speech.DeletePhraseSetRequest], 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._DeletePhraseSet(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_recognizer( + self, + ) -> Callable[[cloud_speech.DeleteRecognizerRequest], 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._DeleteRecognizer(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_config( + self, + ) -> Callable[[cloud_speech.GetConfigRequest], cloud_speech.Config]: + # 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._GetConfig(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_custom_class( + self, + ) -> Callable[[cloud_speech.GetCustomClassRequest], cloud_speech.CustomClass]: + # 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._GetCustomClass(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_phrase_set( + self, + ) -> Callable[[cloud_speech.GetPhraseSetRequest], cloud_speech.PhraseSet]: + # 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._GetPhraseSet(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_recognizer( + self, + ) -> Callable[[cloud_speech.GetRecognizerRequest], cloud_speech.Recognizer]: + # 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._GetRecognizer(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_custom_classes( + self, + ) -> Callable[ + [cloud_speech.ListCustomClassesRequest], cloud_speech.ListCustomClassesResponse + ]: + # 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._ListCustomClasses(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_phrase_sets( + self, + ) -> Callable[ + [cloud_speech.ListPhraseSetsRequest], cloud_speech.ListPhraseSetsResponse + ]: + # 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._ListPhraseSets(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_recognizers( + self, + ) -> Callable[ + [cloud_speech.ListRecognizersRequest], cloud_speech.ListRecognizersResponse + ]: + # 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._ListRecognizers(self._session, self._host, self._interceptor) # type: ignore + + @property + def recognize( + self, + ) -> Callable[[cloud_speech.RecognizeRequest], cloud_speech.RecognizeResponse]: + # 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._Recognize(self._session, self._host, self._interceptor) # type: ignore + + @property + def streaming_recognize( + self, + ) -> Callable[ + [cloud_speech.StreamingRecognizeRequest], + cloud_speech.StreamingRecognizeResponse, + ]: + # 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._StreamingRecognize(self._session, self._host, self._interceptor) # type: ignore + + @property + def undelete_custom_class( + self, + ) -> Callable[[cloud_speech.UndeleteCustomClassRequest], 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._UndeleteCustomClass(self._session, self._host, self._interceptor) # type: ignore + + @property + def undelete_phrase_set( + self, + ) -> Callable[[cloud_speech.UndeletePhraseSetRequest], 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._UndeletePhraseSet(self._session, self._host, self._interceptor) # type: ignore + + @property + def undelete_recognizer( + self, + ) -> Callable[[cloud_speech.UndeleteRecognizerRequest], 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._UndeleteRecognizer(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_config( + self, + ) -> Callable[[cloud_speech.UpdateConfigRequest], cloud_speech.Config]: + # 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._UpdateConfig(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_custom_class( + self, + ) -> Callable[[cloud_speech.UpdateCustomClassRequest], 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._UpdateCustomClass(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_phrase_set( + self, + ) -> Callable[[cloud_speech.UpdatePhraseSetRequest], 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._UpdatePhraseSet(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_recognizer( + self, + ) -> Callable[[cloud_speech.UpdateRecognizerRequest], 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._UpdateRecognizer(self._session, self._host, self._interceptor) # type: ignore + + @property + def cancel_operation(self): + return self._CancelOperation(self._session, self._host, self._interceptor) # type: ignore + + class _CancelOperation(SpeechRestStub): + def __call__( + self, + request: operations_pb2.CancelOperationRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + + r"""Call the cancel operation method over HTTP. + + Args: + request (operations_pb2.CancelOperationRequest): + The request object for CancelOperation method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v2/{name=projects/*/locations/*/operations/*}:cancel", + "body": "*", + }, + ] + + request, metadata = self._interceptor.pre_cancel_operation( + request, metadata + ) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + + body = json.loads(json.dumps(transcoded_request["body"])) + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + return self._interceptor.post_cancel_operation(None) + + @property + def delete_operation(self): + return self._DeleteOperation(self._session, self._host, self._interceptor) # type: ignore + + class _DeleteOperation(SpeechRestStub): + def __call__( + self, + request: operations_pb2.DeleteOperationRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + + r"""Call the delete operation method over HTTP. + + Args: + request (operations_pb2.DeleteOperationRequest): + The request object for DeleteOperation method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "delete", + "uri": "/v2/{name=projects/*/locations/*/operations/*}", + }, + ] + + request, metadata = self._interceptor.pre_delete_operation( + request, metadata + ) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + return self._interceptor.post_delete_operation(None) + + @property + def get_operation(self): + return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore + + class _GetOperation(SpeechRestStub): + def __call__( + self, + request: operations_pb2.GetOperationRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + + r"""Call the get operation method over HTTP. + + Args: + request (operations_pb2.GetOperationRequest): + The request object for GetOperation method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + operations_pb2.Operation: Response from GetOperation method. + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v2/{name=projects/*/locations/*/operations/*}", + }, + ] + + request, metadata = self._interceptor.pre_get_operation(request, metadata) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + resp = operations_pb2.Operation() + resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = self._interceptor.post_get_operation(resp) + return resp + + @property + def list_operations(self): + return self._ListOperations(self._session, self._host, self._interceptor) # type: ignore + + class _ListOperations(SpeechRestStub): + def __call__( + self, + request: operations_pb2.ListOperationsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.ListOperationsResponse: + + r"""Call the list operations method over HTTP. + + Args: + request (operations_pb2.ListOperationsRequest): + The request object for ListOperations method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + operations_pb2.ListOperationsResponse: Response from ListOperations method. + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v2/{name=projects/*/locations/*}/operations", + }, + ] + + request, metadata = self._interceptor.pre_list_operations(request, metadata) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + resp = operations_pb2.ListOperationsResponse() + resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = self._interceptor.post_list_operations(resp) + return resp + + @property + def kind(self) -> str: + return "rest" + + def close(self): + self._session.close() + + +__all__ = ("SpeechRestTransport",) diff --git a/google/cloud/speech_v2/types/cloud_speech.py b/google/cloud/speech_v2/types/cloud_speech.py index d711cd5b..07eb6e90 100644 --- a/google/cloud/speech_v2/types/cloud_speech.py +++ b/google/cloud/speech_v2/types/cloud_speech.py @@ -13,6 +13,8 @@ # See the License for the specific language governing permissions and # limitations under the License. # +from __future__ import annotations + from typing import MutableMapping, MutableSequence import proto # type: ignore diff --git a/samples/generated_samples/snippet_metadata_google.cloud.speech.v1.json b/samples/generated_samples/snippet_metadata_google.cloud.speech.v1.json index d44e56f1..bd6f09cb 100644 --- a/samples/generated_samples/snippet_metadata_google.cloud.speech.v1.json +++ b/samples/generated_samples/snippet_metadata_google.cloud.speech.v1.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-speech", - "version": "2.17.3" + "version": "2.18.0" }, "snippets": [ { diff --git a/samples/generated_samples/snippet_metadata_google.cloud.speech.v1p1beta1.json b/samples/generated_samples/snippet_metadata_google.cloud.speech.v1p1beta1.json index 842bb4bf..c2bbddc0 100644 --- a/samples/generated_samples/snippet_metadata_google.cloud.speech.v1p1beta1.json +++ b/samples/generated_samples/snippet_metadata_google.cloud.speech.v1p1beta1.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-speech", - "version": "2.17.3" + "version": "2.18.0" }, "snippets": [ { diff --git a/samples/generated_samples/snippet_metadata_google.cloud.speech.v2.json b/samples/generated_samples/snippet_metadata_google.cloud.speech.v2.json index 055d73ab..f18f2c5a 100644 --- a/samples/generated_samples/snippet_metadata_google.cloud.speech.v2.json +++ b/samples/generated_samples/snippet_metadata_google.cloud.speech.v2.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-speech", - "version": "2.17.3" + "version": "2.18.0" }, "snippets": [ { diff --git a/samples/microphone/requirements.txt b/samples/microphone/requirements.txt index 699e6154..d39b69bb 100644 --- a/samples/microphone/requirements.txt +++ b/samples/microphone/requirements.txt @@ -1,4 +1,4 @@ -google-cloud-speech==2.17.2 +google-cloud-speech==2.17.3 pyaudio==0.2.13 six==1.16.0 diff --git a/samples/snippets/requirements.txt b/samples/snippets/requirements.txt index d507aa14..b8f62a4a 100644 --- a/samples/snippets/requirements.txt +++ b/samples/snippets/requirements.txt @@ -1,2 +1,2 @@ -google-cloud-speech==2.17.2 +google-cloud-speech==2.17.3 google-cloud-storage==2.7.0 diff --git a/setup.py b/setup.py index 4fdce7e2..9483e31d 100644 --- a/setup.py +++ b/setup.py @@ -55,9 +55,7 @@ if package.startswith("google") ] -namespaces = ["google"] -if "google.cloud" in packages: - namespaces.append("google.cloud") +namespaces = ["google", "google.cloud"] setuptools.setup( name=name, diff --git a/tests/unit/gapic/speech_v1/test_adaptation.py b/tests/unit/gapic/speech_v1/test_adaptation.py index 2c662dec..5a9f90b8 100644 --- a/tests/unit/gapic/speech_v1/test_adaptation.py +++ b/tests/unit/gapic/speech_v1/test_adaptation.py @@ -24,10 +24,17 @@ import grpc from grpc.experimental import aio +from collections.abc import Iterable +from google.protobuf import json_format +import json import math import pytest from proto.marshal.rules.dates import DurationRule, TimestampRule from proto.marshal.rules import wrappers +from requests import Response +from requests import Request, PreparedRequest +from requests.sessions import Session +from google.protobuf import json_format from google.api_core import client_options from google.api_core import exceptions as core_exceptions @@ -95,6 +102,7 @@ def test__get_default_mtls_endpoint(): [ (AdaptationClient, "grpc"), (AdaptationAsyncClient, "grpc_asyncio"), + (AdaptationClient, "rest"), ], ) def test_adaptation_client_from_service_account_info(client_class, transport_name): @@ -108,7 +116,11 @@ def test_adaptation_client_from_service_account_info(client_class, transport_nam assert client.transport._credentials == creds assert isinstance(client, client_class) - assert client.transport._host == ("speech.googleapis.com:443") + assert client.transport._host == ( + "speech.googleapis.com:443" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://speech.googleapis.com" + ) @pytest.mark.parametrize( @@ -116,6 +128,7 @@ def test_adaptation_client_from_service_account_info(client_class, transport_nam [ (transports.AdaptationGrpcTransport, "grpc"), (transports.AdaptationGrpcAsyncIOTransport, "grpc_asyncio"), + (transports.AdaptationRestTransport, "rest"), ], ) def test_adaptation_client_service_account_always_use_jwt( @@ -141,6 +154,7 @@ def test_adaptation_client_service_account_always_use_jwt( [ (AdaptationClient, "grpc"), (AdaptationAsyncClient, "grpc_asyncio"), + (AdaptationClient, "rest"), ], ) def test_adaptation_client_from_service_account_file(client_class, transport_name): @@ -161,13 +175,18 @@ def test_adaptation_client_from_service_account_file(client_class, transport_nam assert client.transport._credentials == creds assert isinstance(client, client_class) - assert client.transport._host == ("speech.googleapis.com:443") + assert client.transport._host == ( + "speech.googleapis.com:443" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://speech.googleapis.com" + ) def test_adaptation_client_get_transport_class(): transport = AdaptationClient.get_transport_class() available_transports = [ transports.AdaptationGrpcTransport, + transports.AdaptationRestTransport, ] assert transport in available_transports @@ -184,6 +203,7 @@ def test_adaptation_client_get_transport_class(): transports.AdaptationGrpcAsyncIOTransport, "grpc_asyncio", ), + (AdaptationClient, transports.AdaptationRestTransport, "rest"), ], ) @mock.patch.object( @@ -327,6 +347,8 @@ def test_adaptation_client_client_options( "grpc_asyncio", "false", ), + (AdaptationClient, transports.AdaptationRestTransport, "rest", "true"), + (AdaptationClient, transports.AdaptationRestTransport, "rest", "false"), ], ) @mock.patch.object( @@ -520,6 +542,7 @@ def test_adaptation_client_get_mtls_endpoint_and_cert_source(client_class): transports.AdaptationGrpcAsyncIOTransport, "grpc_asyncio", ), + (AdaptationClient, transports.AdaptationRestTransport, "rest"), ], ) def test_adaptation_client_client_options_scopes( @@ -555,6 +578,7 @@ def test_adaptation_client_client_options_scopes( "grpc_asyncio", grpc_helpers_async, ), + (AdaptationClient, transports.AdaptationRestTransport, "rest", None), ], ) def test_adaptation_client_client_options_credentials_file( @@ -3520,208 +3544,3101 @@ async def test_delete_custom_class_flattened_error_async(): ) -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.AdaptationGrpcTransport( +@pytest.mark.parametrize( + "request_type", + [ + cloud_speech_adaptation.CreatePhraseSetRequest, + dict, + ], +) +def test_create_phrase_set_rest(request_type): + client = AdaptationClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - with pytest.raises(ValueError): - client = AdaptationClient( - 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 response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = resource.PhraseSet( + name="name_value", + boost=0.551, ) - # It is an error to provide a credentials file and a transport instance. - transport = transports.AdaptationGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = AdaptationClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = resource.PhraseSet.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.create_phrase_set(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, resource.PhraseSet) + assert response.name == "name_value" + assert math.isclose(response.boost, 0.551, rel_tol=1e-6) + + +def test_create_phrase_set_rest_required_fields( + request_type=cloud_speech_adaptation.CreatePhraseSetRequest, +): + transport_class = transports.AdaptationRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["phrase_set_id"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False, ) + ) - # It is an error to provide an api_key and a transport instance. - transport = transports.AdaptationGrpcTransport( + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).create_phrase_set._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["phraseSetId"] = "phrase_set_id_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).create_phrase_set._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 "phraseSetId" in jsonified_request + assert jsonified_request["phraseSetId"] == "phrase_set_id_value" + + client = AdaptationClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = resource.PhraseSet() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force 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 + + pb_return_value = resource.PhraseSet.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.create_phrase_set(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_create_phrase_set_rest_unset_required_fields(): + transport = transports.AdaptationRestTransport( + credentials=ga_credentials.AnonymousCredentials ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = AdaptationClient( - client_options=options, - transport=transport, - ) - # It is an error to provide an api_key and a credential. - options = mock.Mock() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = AdaptationClient( - client_options=options, credentials=ga_credentials.AnonymousCredentials() + unset_fields = transport.create_phrase_set._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(()) + & set( + ( + "parent", + "phraseSetId", + "phraseSet", + ) ) + ) - # It is an error to provide scopes and a transport instance. - transport = transports.AdaptationGrpcTransport( + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_phrase_set_rest_interceptors(null_interceptor): + transport = transports.AdaptationRestTransport( credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.AdaptationRestInterceptor(), ) - with pytest.raises(ValueError): - client = AdaptationClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, + client = AdaptationClient(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.AdaptationRestInterceptor, "post_create_phrase_set" + ) as post, mock.patch.object( + transports.AdaptationRestInterceptor, "pre_create_phrase_set" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = cloud_speech_adaptation.CreatePhraseSetRequest.pb( + cloud_speech_adaptation.CreatePhraseSetRequest() ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = resource.PhraseSet.to_json(resource.PhraseSet()) + + request = cloud_speech_adaptation.CreatePhraseSetRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = resource.PhraseSet() + client.create_phrase_set( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.AdaptationGrpcTransport( + pre.assert_called_once() + post.assert_called_once() + + +def test_create_phrase_set_rest_bad_request( + transport: str = "rest", request_type=cloud_speech_adaptation.CreatePhraseSetRequest +): + client = AdaptationClient( credentials=ga_credentials.AnonymousCredentials(), + transport=transport, ) - client = AdaptationClient(transport=transport) - assert client.transport is transport + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2"} + request = request_type(**request_init) -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.AdaptationGrpcTransport( + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.create_phrase_set(request) + + +def test_create_phrase_set_rest_flattened(): + client = AdaptationClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - channel = transport.grpc_channel - assert channel - transport = transports.AdaptationGrpcAsyncIOTransport( + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = resource.PhraseSet() + + # 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", + phrase_set=resource.PhraseSet(name="name_value"), + phrase_set_id="phrase_set_id_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = resource.PhraseSet.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.create_phrase_set(**mock_args) + + # Establish that the underlying call was 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/*}/phraseSets" % client.transport._host, + args[1], + ) + + +def test_create_phrase_set_rest_flattened_error(transport: str = "rest"): + client = AdaptationClient( credentials=ga_credentials.AnonymousCredentials(), + transport=transport, ) - channel = transport.grpc_channel - assert channel + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.create_phrase_set( + cloud_speech_adaptation.CreatePhraseSetRequest(), + parent="parent_value", + phrase_set=resource.PhraseSet(name="name_value"), + phrase_set_id="phrase_set_id_value", + ) -@pytest.mark.parametrize( - "transport_class", - [ - transports.AdaptationGrpcTransport, - transports.AdaptationGrpcAsyncIOTransport, - ], -) -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_create_phrase_set_rest_error(): + client = AdaptationClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) @pytest.mark.parametrize( - "transport_name", + "request_type", [ - "grpc", + cloud_speech_adaptation.GetPhraseSetRequest, + dict, ], ) -def test_transport_kind(transport_name): - transport = AdaptationClient.get_transport_class(transport_name)( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert transport.kind == transport_name - - -def test_transport_grpc_default(): - # A client should use the gRPC transport by default. +def test_get_phrase_set_rest(request_type): client = AdaptationClient( credentials=ga_credentials.AnonymousCredentials(), - ) - assert isinstance( - client.transport, - transports.AdaptationGrpcTransport, + transport="rest", ) + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/phraseSets/sample3"} + request = request_type(**request_init) -def test_adaptation_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.AdaptationTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json", + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = resource.PhraseSet( + name="name_value", + boost=0.551, ) + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = resource.PhraseSet.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) -def test_adaptation_base_transport(): - # Instantiate the base transport. - with mock.patch( - "google.cloud.speech_v1.services.adaptation.transports.AdaptationTransport.__init__" - ) as Transport: - Transport.return_value = None - transport = transports.AdaptationTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.get_phrase_set(request) - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - "create_phrase_set", - "get_phrase_set", - "list_phrase_set", - "update_phrase_set", - "delete_phrase_set", - "create_custom_class", - "get_custom_class", - "list_custom_classes", - "update_custom_class", - "delete_custom_class", - "get_operation", - "list_operations", + # Establish that the response is the type that we expect. + assert isinstance(response, resource.PhraseSet) + assert response.name == "name_value" + assert math.isclose(response.boost, 0.551, rel_tol=1e-6) + + +def test_get_phrase_set_rest_required_fields( + request_type=cloud_speech_adaptation.GetPhraseSetRequest, +): + transport_class = transports.AdaptationRestTransport + + 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, + including_default_value_fields=False, + use_integers_for_enums=False, + ) ) - for method in methods: - with pytest.raises(NotImplementedError): - getattr(transport, method)(request=object()) - with pytest.raises(NotImplementedError): - transport.close() + # verify fields with default values are dropped - # Catch all for all remaining methods and properties - remainder = [ - "kind", - ] - for r in remainder: - with pytest.raises(NotImplementedError): - getattr(transport, r)() + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get_phrase_set._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + # verify required fields with default values are now present -def test_adaptation_base_transport_with_credentials_file(): - # Instantiate the base transport with a credentials file - with mock.patch.object( - google.auth, "load_credentials_from_file", autospec=True - ) as load_creds, mock.patch( - "google.cloud.speech_v1.services.adaptation.transports.AdaptationTransport._prep_wrapped_messages" - ) as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.AdaptationTransport( - credentials_file="credentials.json", - quota_project_id="octopus", - ) - load_creds.assert_called_once_with( - "credentials.json", - scopes=None, - default_scopes=("https://www.googleapis.com/auth/cloud-platform",), - quota_project_id="octopus", - ) + jsonified_request["name"] = "name_value" + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get_phrase_set._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) -def test_adaptation_base_transport_with_adc(): - # Test the default credentials are used if credentials and credentials_file are None. - with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch( - "google.cloud.speech_v1.services.adaptation.transports.AdaptationTransport._prep_wrapped_messages" - ) as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.AdaptationTransport() - adc.assert_called_once() + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + client = AdaptationClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = resource.PhraseSet() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force 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 -def test_adaptation_auth_adc(): - # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(google.auth, "default", autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) + response_value = Response() + response_value.status_code = 200 + + pb_return_value = resource.PhraseSet.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.get_phrase_set(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_get_phrase_set_rest_unset_required_fields(): + transport = transports.AdaptationRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.get_phrase_set._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_phrase_set_rest_interceptors(null_interceptor): + transport = transports.AdaptationRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.AdaptationRestInterceptor(), + ) + client = AdaptationClient(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.AdaptationRestInterceptor, "post_get_phrase_set" + ) as post, mock.patch.object( + transports.AdaptationRestInterceptor, "pre_get_phrase_set" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = cloud_speech_adaptation.GetPhraseSetRequest.pb( + cloud_speech_adaptation.GetPhraseSetRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = resource.PhraseSet.to_json(resource.PhraseSet()) + + request = cloud_speech_adaptation.GetPhraseSetRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = resource.PhraseSet() + + client.get_phrase_set( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_phrase_set_rest_bad_request( + transport: str = "rest", request_type=cloud_speech_adaptation.GetPhraseSetRequest +): + client = AdaptationClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/phraseSets/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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_phrase_set(request) + + +def test_get_phrase_set_rest_flattened(): + client = AdaptationClient( + 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 = resource.PhraseSet() + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/phraseSets/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 + pb_return_value = resource.PhraseSet.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.get_phrase_set(**mock_args) + + # Establish that the underlying call was 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/*/phraseSets/*}" % client.transport._host, + args[1], + ) + + +def test_get_phrase_set_rest_flattened_error(transport: str = "rest"): + client = AdaptationClient( + credentials=ga_credentials.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_phrase_set( + cloud_speech_adaptation.GetPhraseSetRequest(), + name="name_value", + ) + + +def test_get_phrase_set_rest_error(): + client = AdaptationClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + cloud_speech_adaptation.ListPhraseSetRequest, + dict, + ], +) +def test_list_phrase_set_rest(request_type): + client = AdaptationClient( + 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 = cloud_speech_adaptation.ListPhraseSetResponse( + next_page_token="next_page_token_value", + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = cloud_speech_adaptation.ListPhraseSetResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.list_phrase_set(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListPhraseSetPager) + assert response.next_page_token == "next_page_token_value" + + +def test_list_phrase_set_rest_required_fields( + request_type=cloud_speech_adaptation.ListPhraseSetRequest, +): + transport_class = transports.AdaptationRestTransport + + 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, + including_default_value_fields=False, + use_integers_for_enums=False, + ) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).list_phrase_set._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = "parent_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).list_phrase_set._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "page_size", + "page_token", + ) + ) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + + client = AdaptationClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = cloud_speech_adaptation.ListPhraseSetResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force 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 + + pb_return_value = cloud_speech_adaptation.ListPhraseSetResponse.pb( + return_value + ) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.list_phrase_set(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_list_phrase_set_rest_unset_required_fields(): + transport = transports.AdaptationRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.list_phrase_set._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "pageSize", + "pageToken", + ) + ) + & set(("parent",)) + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_phrase_set_rest_interceptors(null_interceptor): + transport = transports.AdaptationRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.AdaptationRestInterceptor(), + ) + client = AdaptationClient(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.AdaptationRestInterceptor, "post_list_phrase_set" + ) as post, mock.patch.object( + transports.AdaptationRestInterceptor, "pre_list_phrase_set" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = cloud_speech_adaptation.ListPhraseSetRequest.pb( + cloud_speech_adaptation.ListPhraseSetRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = ( + cloud_speech_adaptation.ListPhraseSetResponse.to_json( + cloud_speech_adaptation.ListPhraseSetResponse() + ) + ) + + request = cloud_speech_adaptation.ListPhraseSetRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = cloud_speech_adaptation.ListPhraseSetResponse() + + client.list_phrase_set( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_phrase_set_rest_bad_request( + transport: str = "rest", request_type=cloud_speech_adaptation.ListPhraseSetRequest +): + client = AdaptationClient( + 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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_phrase_set(request) + + +def test_list_phrase_set_rest_flattened(): + client = AdaptationClient( + 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 = cloud_speech_adaptation.ListPhraseSetResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {"parent": "projects/sample1/locations/sample2"} + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = cloud_speech_adaptation.ListPhraseSetResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.list_phrase_set(**mock_args) + + # Establish that the underlying call was 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/*}/phraseSets" % client.transport._host, + args[1], + ) + + +def test_list_phrase_set_rest_flattened_error(transport: str = "rest"): + client = AdaptationClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_phrase_set( + cloud_speech_adaptation.ListPhraseSetRequest(), + parent="parent_value", + ) + + +def test_list_phrase_set_rest_pager(transport: str = "rest"): + client = AdaptationClient( + 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 = ( + cloud_speech_adaptation.ListPhraseSetResponse( + phrase_sets=[ + resource.PhraseSet(), + resource.PhraseSet(), + resource.PhraseSet(), + ], + next_page_token="abc", + ), + cloud_speech_adaptation.ListPhraseSetResponse( + phrase_sets=[], + next_page_token="def", + ), + cloud_speech_adaptation.ListPhraseSetResponse( + phrase_sets=[ + resource.PhraseSet(), + ], + next_page_token="ghi", + ), + cloud_speech_adaptation.ListPhraseSetResponse( + phrase_sets=[ + resource.PhraseSet(), + resource.PhraseSet(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple( + cloud_speech_adaptation.ListPhraseSetResponse.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_phrase_set(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, resource.PhraseSet) for i in results) + + pages = list(client.list_phrase_set(request=sample_request).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.parametrize( + "request_type", + [ + cloud_speech_adaptation.UpdatePhraseSetRequest, + dict, + ], +) +def test_update_phrase_set_rest(request_type): + client = AdaptationClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = { + "phrase_set": {"name": "projects/sample1/locations/sample2/phraseSets/sample3"} + } + request_init["phrase_set"] = { + "name": "projects/sample1/locations/sample2/phraseSets/sample3", + "phrases": [{"value": "value_value", "boost": 0.551}], + "boost": 0.551, + } + 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 = resource.PhraseSet( + name="name_value", + boost=0.551, + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = resource.PhraseSet.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.update_phrase_set(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, resource.PhraseSet) + assert response.name == "name_value" + assert math.isclose(response.boost, 0.551, rel_tol=1e-6) + + +def test_update_phrase_set_rest_required_fields( + request_type=cloud_speech_adaptation.UpdatePhraseSetRequest, +): + transport_class = transports.AdaptationRestTransport + + request_init = {} + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False, + ) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).update_phrase_set._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).update_phrase_set._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("update_mask",)) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + + client = AdaptationClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = resource.PhraseSet() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "patch", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + pb_return_value = resource.PhraseSet.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.update_phrase_set(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_update_phrase_set_rest_unset_required_fields(): + transport = transports.AdaptationRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.update_phrase_set._get_unset_required_fields({}) + assert set(unset_fields) == (set(("updateMask",)) & set(("phraseSet",))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_phrase_set_rest_interceptors(null_interceptor): + transport = transports.AdaptationRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.AdaptationRestInterceptor(), + ) + client = AdaptationClient(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.AdaptationRestInterceptor, "post_update_phrase_set" + ) as post, mock.patch.object( + transports.AdaptationRestInterceptor, "pre_update_phrase_set" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = cloud_speech_adaptation.UpdatePhraseSetRequest.pb( + cloud_speech_adaptation.UpdatePhraseSetRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = resource.PhraseSet.to_json(resource.PhraseSet()) + + request = cloud_speech_adaptation.UpdatePhraseSetRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = resource.PhraseSet() + + client.update_phrase_set( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_phrase_set_rest_bad_request( + transport: str = "rest", request_type=cloud_speech_adaptation.UpdatePhraseSetRequest +): + client = AdaptationClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = { + "phrase_set": {"name": "projects/sample1/locations/sample2/phraseSets/sample3"} + } + request_init["phrase_set"] = { + "name": "projects/sample1/locations/sample2/phraseSets/sample3", + "phrases": [{"value": "value_value", "boost": 0.551}], + "boost": 0.551, + } + 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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.update_phrase_set(request) + + +def test_update_phrase_set_rest_flattened(): + client = AdaptationClient( + 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 = resource.PhraseSet() + + # get arguments that satisfy an http rule for this method + sample_request = { + "phrase_set": { + "name": "projects/sample1/locations/sample2/phraseSets/sample3" + } + } + + # get truthy value for each flattened field + mock_args = dict( + phrase_set=resource.PhraseSet(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 + pb_return_value = resource.PhraseSet.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.update_phrase_set(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1/{phrase_set.name=projects/*/locations/*/phraseSets/*}" + % client.transport._host, + args[1], + ) + + +def test_update_phrase_set_rest_flattened_error(transport: str = "rest"): + client = AdaptationClient( + credentials=ga_credentials.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_phrase_set( + cloud_speech_adaptation.UpdatePhraseSetRequest(), + phrase_set=resource.PhraseSet(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +def test_update_phrase_set_rest_error(): + client = AdaptationClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + cloud_speech_adaptation.DeletePhraseSetRequest, + dict, + ], +) +def test_delete_phrase_set_rest(request_type): + client = AdaptationClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/phraseSets/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 = None + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = "" + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.delete_phrase_set(request) + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_phrase_set_rest_required_fields( + request_type=cloud_speech_adaptation.DeletePhraseSetRequest, +): + transport_class = transports.AdaptationRestTransport + + 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, + including_default_value_fields=False, + use_integers_for_enums=False, + ) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).delete_phrase_set._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_phrase_set._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 = AdaptationClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = None + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "delete", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = "" + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.delete_phrase_set(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_delete_phrase_set_rest_unset_required_fields(): + transport = transports.AdaptationRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.delete_phrase_set._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_phrase_set_rest_interceptors(null_interceptor): + transport = transports.AdaptationRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.AdaptationRestInterceptor(), + ) + client = AdaptationClient(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.AdaptationRestInterceptor, "pre_delete_phrase_set" + ) as pre: + pre.assert_not_called() + pb_message = cloud_speech_adaptation.DeletePhraseSetRequest.pb( + cloud_speech_adaptation.DeletePhraseSetRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + + request = cloud_speech_adaptation.DeletePhraseSetRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + + client.delete_phrase_set( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + + +def test_delete_phrase_set_rest_bad_request( + transport: str = "rest", request_type=cloud_speech_adaptation.DeletePhraseSetRequest +): + client = AdaptationClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/phraseSets/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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.delete_phrase_set(request) + + +def test_delete_phrase_set_rest_flattened(): + client = AdaptationClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = None + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/phraseSets/sample3" + } + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = "" + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.delete_phrase_set(**mock_args) + + # Establish that the underlying call was 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/*/phraseSets/*}" % client.transport._host, + args[1], + ) + + +def test_delete_phrase_set_rest_flattened_error(transport: str = "rest"): + client = AdaptationClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.delete_phrase_set( + cloud_speech_adaptation.DeletePhraseSetRequest(), + name="name_value", + ) + + +def test_delete_phrase_set_rest_error(): + client = AdaptationClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + cloud_speech_adaptation.CreateCustomClassRequest, + dict, + ], +) +def test_create_custom_class_rest(request_type): + client = AdaptationClient( + 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 = resource.CustomClass( + name="name_value", + custom_class_id="custom_class_id_value", + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = resource.CustomClass.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.create_custom_class(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, resource.CustomClass) + assert response.name == "name_value" + assert response.custom_class_id == "custom_class_id_value" + + +def test_create_custom_class_rest_required_fields( + request_type=cloud_speech_adaptation.CreateCustomClassRequest, +): + transport_class = transports.AdaptationRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["custom_class_id"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False, + ) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).create_custom_class._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["customClassId"] = "custom_class_id_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).create_custom_class._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 "customClassId" in jsonified_request + assert jsonified_request["customClassId"] == "custom_class_id_value" + + client = AdaptationClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = resource.CustomClass() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force 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 + + pb_return_value = resource.CustomClass.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.create_custom_class(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_create_custom_class_rest_unset_required_fields(): + transport = transports.AdaptationRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.create_custom_class._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(()) + & set( + ( + "parent", + "customClassId", + "customClass", + ) + ) + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_custom_class_rest_interceptors(null_interceptor): + transport = transports.AdaptationRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.AdaptationRestInterceptor(), + ) + client = AdaptationClient(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.AdaptationRestInterceptor, "post_create_custom_class" + ) as post, mock.patch.object( + transports.AdaptationRestInterceptor, "pre_create_custom_class" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = cloud_speech_adaptation.CreateCustomClassRequest.pb( + cloud_speech_adaptation.CreateCustomClassRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = resource.CustomClass.to_json(resource.CustomClass()) + + request = cloud_speech_adaptation.CreateCustomClassRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = resource.CustomClass() + + client.create_custom_class( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_create_custom_class_rest_bad_request( + transport: str = "rest", + request_type=cloud_speech_adaptation.CreateCustomClassRequest, +): + client = AdaptationClient( + 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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.create_custom_class(request) + + +def test_create_custom_class_rest_flattened(): + client = AdaptationClient( + 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 = resource.CustomClass() + + # 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", + custom_class=resource.CustomClass(name="name_value"), + custom_class_id="custom_class_id_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = resource.CustomClass.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.create_custom_class(**mock_args) + + # Establish that the underlying call was 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/*}/customClasses" + % client.transport._host, + args[1], + ) + + +def test_create_custom_class_rest_flattened_error(transport: str = "rest"): + client = AdaptationClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.create_custom_class( + cloud_speech_adaptation.CreateCustomClassRequest(), + parent="parent_value", + custom_class=resource.CustomClass(name="name_value"), + custom_class_id="custom_class_id_value", + ) + + +def test_create_custom_class_rest_error(): + client = AdaptationClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + cloud_speech_adaptation.GetCustomClassRequest, + dict, + ], +) +def test_get_custom_class_rest(request_type): + client = AdaptationClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/customClasses/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 = resource.CustomClass( + name="name_value", + custom_class_id="custom_class_id_value", + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = resource.CustomClass.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.get_custom_class(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, resource.CustomClass) + assert response.name == "name_value" + assert response.custom_class_id == "custom_class_id_value" + + +def test_get_custom_class_rest_required_fields( + request_type=cloud_speech_adaptation.GetCustomClassRequest, +): + transport_class = transports.AdaptationRestTransport + + 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, + including_default_value_fields=False, + use_integers_for_enums=False, + ) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get_custom_class._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_custom_class._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 = AdaptationClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = resource.CustomClass() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force 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 + + pb_return_value = resource.CustomClass.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.get_custom_class(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_get_custom_class_rest_unset_required_fields(): + transport = transports.AdaptationRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.get_custom_class._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_custom_class_rest_interceptors(null_interceptor): + transport = transports.AdaptationRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.AdaptationRestInterceptor(), + ) + client = AdaptationClient(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.AdaptationRestInterceptor, "post_get_custom_class" + ) as post, mock.patch.object( + transports.AdaptationRestInterceptor, "pre_get_custom_class" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = cloud_speech_adaptation.GetCustomClassRequest.pb( + cloud_speech_adaptation.GetCustomClassRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = resource.CustomClass.to_json(resource.CustomClass()) + + request = cloud_speech_adaptation.GetCustomClassRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = resource.CustomClass() + + client.get_custom_class( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_custom_class_rest_bad_request( + transport: str = "rest", request_type=cloud_speech_adaptation.GetCustomClassRequest +): + client = AdaptationClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/customClasses/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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_custom_class(request) + + +def test_get_custom_class_rest_flattened(): + client = AdaptationClient( + 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 = resource.CustomClass() + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/customClasses/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 + pb_return_value = resource.CustomClass.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.get_custom_class(**mock_args) + + # Establish that the underlying call was 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/*/customClasses/*}" + % client.transport._host, + args[1], + ) + + +def test_get_custom_class_rest_flattened_error(transport: str = "rest"): + client = AdaptationClient( + credentials=ga_credentials.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_custom_class( + cloud_speech_adaptation.GetCustomClassRequest(), + name="name_value", + ) + + +def test_get_custom_class_rest_error(): + client = AdaptationClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + cloud_speech_adaptation.ListCustomClassesRequest, + dict, + ], +) +def test_list_custom_classes_rest(request_type): + client = AdaptationClient( + 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 = cloud_speech_adaptation.ListCustomClassesResponse( + next_page_token="next_page_token_value", + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = cloud_speech_adaptation.ListCustomClassesResponse.pb( + return_value + ) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.list_custom_classes(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListCustomClassesPager) + assert response.next_page_token == "next_page_token_value" + + +def test_list_custom_classes_rest_required_fields( + request_type=cloud_speech_adaptation.ListCustomClassesRequest, +): + transport_class = transports.AdaptationRestTransport + + 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, + including_default_value_fields=False, + use_integers_for_enums=False, + ) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).list_custom_classes._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = "parent_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).list_custom_classes._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "page_size", + "page_token", + ) + ) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + + client = AdaptationClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = cloud_speech_adaptation.ListCustomClassesResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force 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 + + pb_return_value = cloud_speech_adaptation.ListCustomClassesResponse.pb( + return_value + ) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.list_custom_classes(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_list_custom_classes_rest_unset_required_fields(): + transport = transports.AdaptationRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.list_custom_classes._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "pageSize", + "pageToken", + ) + ) + & set(("parent",)) + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_custom_classes_rest_interceptors(null_interceptor): + transport = transports.AdaptationRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.AdaptationRestInterceptor(), + ) + client = AdaptationClient(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.AdaptationRestInterceptor, "post_list_custom_classes" + ) as post, mock.patch.object( + transports.AdaptationRestInterceptor, "pre_list_custom_classes" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = cloud_speech_adaptation.ListCustomClassesRequest.pb( + cloud_speech_adaptation.ListCustomClassesRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = ( + cloud_speech_adaptation.ListCustomClassesResponse.to_json( + cloud_speech_adaptation.ListCustomClassesResponse() + ) + ) + + request = cloud_speech_adaptation.ListCustomClassesRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = cloud_speech_adaptation.ListCustomClassesResponse() + + client.list_custom_classes( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_custom_classes_rest_bad_request( + transport: str = "rest", + request_type=cloud_speech_adaptation.ListCustomClassesRequest, +): + client = AdaptationClient( + 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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_custom_classes(request) + + +def test_list_custom_classes_rest_flattened(): + client = AdaptationClient( + 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 = cloud_speech_adaptation.ListCustomClassesResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {"parent": "projects/sample1/locations/sample2"} + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = cloud_speech_adaptation.ListCustomClassesResponse.pb( + return_value + ) + json_return_value = json_format.MessageToJson(pb_return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.list_custom_classes(**mock_args) + + # Establish that the underlying call was 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/*}/customClasses" + % client.transport._host, + args[1], + ) + + +def test_list_custom_classes_rest_flattened_error(transport: str = "rest"): + client = AdaptationClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_custom_classes( + cloud_speech_adaptation.ListCustomClassesRequest(), + parent="parent_value", + ) + + +def test_list_custom_classes_rest_pager(transport: str = "rest"): + client = AdaptationClient( + 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 = ( + cloud_speech_adaptation.ListCustomClassesResponse( + custom_classes=[ + resource.CustomClass(), + resource.CustomClass(), + resource.CustomClass(), + ], + next_page_token="abc", + ), + cloud_speech_adaptation.ListCustomClassesResponse( + custom_classes=[], + next_page_token="def", + ), + cloud_speech_adaptation.ListCustomClassesResponse( + custom_classes=[ + resource.CustomClass(), + ], + next_page_token="ghi", + ), + cloud_speech_adaptation.ListCustomClassesResponse( + custom_classes=[ + resource.CustomClass(), + resource.CustomClass(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple( + cloud_speech_adaptation.ListCustomClassesResponse.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_custom_classes(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, resource.CustomClass) for i in results) + + pages = list(client.list_custom_classes(request=sample_request).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.parametrize( + "request_type", + [ + cloud_speech_adaptation.UpdateCustomClassRequest, + dict, + ], +) +def test_update_custom_class_rest(request_type): + client = AdaptationClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = { + "custom_class": { + "name": "projects/sample1/locations/sample2/customClasses/sample3" + } + } + request_init["custom_class"] = { + "name": "projects/sample1/locations/sample2/customClasses/sample3", + "custom_class_id": "custom_class_id_value", + "items": [{"value": "value_value"}], + } + 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 = resource.CustomClass( + name="name_value", + custom_class_id="custom_class_id_value", + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = resource.CustomClass.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.update_custom_class(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, resource.CustomClass) + assert response.name == "name_value" + assert response.custom_class_id == "custom_class_id_value" + + +def test_update_custom_class_rest_required_fields( + request_type=cloud_speech_adaptation.UpdateCustomClassRequest, +): + transport_class = transports.AdaptationRestTransport + + request_init = {} + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False, + ) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).update_custom_class._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).update_custom_class._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("update_mask",)) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + + client = AdaptationClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = resource.CustomClass() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "patch", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + pb_return_value = resource.CustomClass.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.update_custom_class(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_update_custom_class_rest_unset_required_fields(): + transport = transports.AdaptationRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.update_custom_class._get_unset_required_fields({}) + assert set(unset_fields) == (set(("updateMask",)) & set(("customClass",))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_custom_class_rest_interceptors(null_interceptor): + transport = transports.AdaptationRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.AdaptationRestInterceptor(), + ) + client = AdaptationClient(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.AdaptationRestInterceptor, "post_update_custom_class" + ) as post, mock.patch.object( + transports.AdaptationRestInterceptor, "pre_update_custom_class" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = cloud_speech_adaptation.UpdateCustomClassRequest.pb( + cloud_speech_adaptation.UpdateCustomClassRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = resource.CustomClass.to_json(resource.CustomClass()) + + request = cloud_speech_adaptation.UpdateCustomClassRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = resource.CustomClass() + + client.update_custom_class( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_custom_class_rest_bad_request( + transport: str = "rest", + request_type=cloud_speech_adaptation.UpdateCustomClassRequest, +): + client = AdaptationClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = { + "custom_class": { + "name": "projects/sample1/locations/sample2/customClasses/sample3" + } + } + request_init["custom_class"] = { + "name": "projects/sample1/locations/sample2/customClasses/sample3", + "custom_class_id": "custom_class_id_value", + "items": [{"value": "value_value"}], + } + 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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.update_custom_class(request) + + +def test_update_custom_class_rest_flattened(): + client = AdaptationClient( + 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 = resource.CustomClass() + + # get arguments that satisfy an http rule for this method + sample_request = { + "custom_class": { + "name": "projects/sample1/locations/sample2/customClasses/sample3" + } + } + + # get truthy value for each flattened field + mock_args = dict( + custom_class=resource.CustomClass(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 + pb_return_value = resource.CustomClass.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.update_custom_class(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1/{custom_class.name=projects/*/locations/*/customClasses/*}" + % client.transport._host, + args[1], + ) + + +def test_update_custom_class_rest_flattened_error(transport: str = "rest"): + client = AdaptationClient( + credentials=ga_credentials.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_custom_class( + cloud_speech_adaptation.UpdateCustomClassRequest(), + custom_class=resource.CustomClass(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +def test_update_custom_class_rest_error(): + client = AdaptationClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + cloud_speech_adaptation.DeleteCustomClassRequest, + dict, + ], +) +def test_delete_custom_class_rest(request_type): + client = AdaptationClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/customClasses/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 = None + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = "" + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.delete_custom_class(request) + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_custom_class_rest_required_fields( + request_type=cloud_speech_adaptation.DeleteCustomClassRequest, +): + transport_class = transports.AdaptationRestTransport + + 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, + including_default_value_fields=False, + use_integers_for_enums=False, + ) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).delete_custom_class._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).delete_custom_class._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 = AdaptationClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = None + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "delete", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = "" + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.delete_custom_class(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_delete_custom_class_rest_unset_required_fields(): + transport = transports.AdaptationRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.delete_custom_class._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_custom_class_rest_interceptors(null_interceptor): + transport = transports.AdaptationRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.AdaptationRestInterceptor(), + ) + client = AdaptationClient(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.AdaptationRestInterceptor, "pre_delete_custom_class" + ) as pre: + pre.assert_not_called() + pb_message = cloud_speech_adaptation.DeleteCustomClassRequest.pb( + cloud_speech_adaptation.DeleteCustomClassRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + + request = cloud_speech_adaptation.DeleteCustomClassRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + + client.delete_custom_class( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + + +def test_delete_custom_class_rest_bad_request( + transport: str = "rest", + request_type=cloud_speech_adaptation.DeleteCustomClassRequest, +): + client = AdaptationClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/customClasses/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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.delete_custom_class(request) + + +def test_delete_custom_class_rest_flattened(): + client = AdaptationClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = None + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/customClasses/sample3" + } + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = "" + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.delete_custom_class(**mock_args) + + # Establish that the underlying call was 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/*/customClasses/*}" + % client.transport._host, + args[1], + ) + + +def test_delete_custom_class_rest_flattened_error(transport: str = "rest"): + client = AdaptationClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.delete_custom_class( + cloud_speech_adaptation.DeleteCustomClassRequest(), + name="name_value", + ) + + +def test_delete_custom_class_rest_error(): + client = AdaptationClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.AdaptationGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = AdaptationClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.AdaptationGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = AdaptationClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.AdaptationGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = AdaptationClient( + client_options=options, + transport=transport, + ) + + # It is an error to provide an api_key and a credential. + options = mock.Mock() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = AdaptationClient( + client_options=options, credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.AdaptationGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = AdaptationClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.AdaptationGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = AdaptationClient(transport=transport) + assert client.transport is transport + + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.AdaptationGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.AdaptationGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.AdaptationGrpcTransport, + transports.AdaptationGrpcAsyncIOTransport, + transports.AdaptationRestTransport, + ], +) +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() + + +@pytest.mark.parametrize( + "transport_name", + [ + "grpc", + "rest", + ], +) +def test_transport_kind(transport_name): + transport = AdaptationClient.get_transport_class(transport_name)( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert transport.kind == transport_name + + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = AdaptationClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.AdaptationGrpcTransport, + ) + + +def test_adaptation_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.AdaptationTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json", + ) + + +def test_adaptation_base_transport(): + # Instantiate the base transport. + with mock.patch( + "google.cloud.speech_v1.services.adaptation.transports.AdaptationTransport.__init__" + ) as Transport: + Transport.return_value = None + transport = transports.AdaptationTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + "create_phrase_set", + "get_phrase_set", + "list_phrase_set", + "update_phrase_set", + "delete_phrase_set", + "create_custom_class", + "get_custom_class", + "list_custom_classes", + "update_custom_class", + "delete_custom_class", + "get_operation", + "list_operations", + ) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + with pytest.raises(NotImplementedError): + transport.close() + + # Catch all for all remaining methods and properties + remainder = [ + "kind", + ] + for r in remainder: + with pytest.raises(NotImplementedError): + getattr(transport, r)() + + +def test_adaptation_base_transport_with_credentials_file(): + # Instantiate the base transport with a credentials file + with mock.patch.object( + google.auth, "load_credentials_from_file", autospec=True + ) as load_creds, mock.patch( + "google.cloud.speech_v1.services.adaptation.transports.AdaptationTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.AdaptationTransport( + credentials_file="credentials.json", + quota_project_id="octopus", + ) + load_creds.assert_called_once_with( + "credentials.json", + scopes=None, + default_scopes=("https://www.googleapis.com/auth/cloud-platform",), + quota_project_id="octopus", + ) + + +def test_adaptation_base_transport_with_adc(): + # Test the default credentials are used if credentials and credentials_file are None. + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch( + "google.cloud.speech_v1.services.adaptation.transports.AdaptationTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.AdaptationTransport() + adc.assert_called_once() + + +def test_adaptation_auth_adc(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) AdaptationClient() adc.assert_called_once_with( scopes=None, @@ -3755,6 +6672,7 @@ def test_adaptation_transport_auth_adc(transport_class): [ transports.AdaptationGrpcTransport, transports.AdaptationGrpcAsyncIOTransport, + transports.AdaptationRestTransport, ], ) def test_adaptation_transport_auth_gdch_credentials(transport_class): @@ -3849,11 +6767,23 @@ def test_adaptation_grpc_transport_client_cert_source_for_mtls(transport_class): ) +def test_adaptation_http_transport_client_cert_source_for_mtls(): + cred = ga_credentials.AnonymousCredentials() + with mock.patch( + "google.auth.transport.requests.AuthorizedSession.configure_mtls_channel" + ) as mock_configure_mtls_channel: + transports.AdaptationRestTransport( + credentials=cred, client_cert_source_for_mtls=client_cert_source_callback + ) + mock_configure_mtls_channel.assert_called_once_with(client_cert_source_callback) + + @pytest.mark.parametrize( "transport_name", [ "grpc", "grpc_asyncio", + "rest", ], ) def test_adaptation_host_no_port(transport_name): @@ -3864,7 +6794,11 @@ def test_adaptation_host_no_port(transport_name): ), transport=transport_name, ) - assert client.transport._host == ("speech.googleapis.com:443") + assert client.transport._host == ( + "speech.googleapis.com:443" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://speech.googleapis.com" + ) @pytest.mark.parametrize( @@ -3872,6 +6806,7 @@ def test_adaptation_host_no_port(transport_name): [ "grpc", "grpc_asyncio", + "rest", ], ) def test_adaptation_host_with_port(transport_name): @@ -3882,7 +6817,60 @@ def test_adaptation_host_with_port(transport_name): ), transport=transport_name, ) - assert client.transport._host == ("speech.googleapis.com:8000") + assert client.transport._host == ( + "speech.googleapis.com:8000" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://speech.googleapis.com:8000" + ) + + +@pytest.mark.parametrize( + "transport_name", + [ + "rest", + ], +) +def test_adaptation_client_transport_session_collision(transport_name): + creds1 = ga_credentials.AnonymousCredentials() + creds2 = ga_credentials.AnonymousCredentials() + client1 = AdaptationClient( + credentials=creds1, + transport=transport_name, + ) + client2 = AdaptationClient( + credentials=creds2, + transport=transport_name, + ) + session1 = client1.transport.create_phrase_set._session + session2 = client2.transport.create_phrase_set._session + assert session1 != session2 + session1 = client1.transport.get_phrase_set._session + session2 = client2.transport.get_phrase_set._session + assert session1 != session2 + session1 = client1.transport.list_phrase_set._session + session2 = client2.transport.list_phrase_set._session + assert session1 != session2 + session1 = client1.transport.update_phrase_set._session + session2 = client2.transport.update_phrase_set._session + assert session1 != session2 + session1 = client1.transport.delete_phrase_set._session + session2 = client2.transport.delete_phrase_set._session + assert session1 != session2 + session1 = client1.transport.create_custom_class._session + session2 = client2.transport.create_custom_class._session + assert session1 != session2 + session1 = client1.transport.get_custom_class._session + session2 = client2.transport.get_custom_class._session + assert session1 != session2 + session1 = client1.transport.list_custom_classes._session + session2 = client2.transport.list_custom_classes._session + assert session1 != session2 + session1 = client1.transport.update_custom_class._session + session2 = client2.transport.update_custom_class._session + assert session1 != session2 + session1 = client1.transport.delete_custom_class._session + session2 = client2.transport.delete_custom_class._session + assert session1 != session2 def test_adaptation_grpc_transport_channel(): @@ -4197,6 +7185,118 @@ async def test_transport_close_async(): close.assert_called_once() +def test_get_operation_rest_bad_request( + transport: str = "rest", request_type=operations_pb2.GetOperationRequest +): + client = AdaptationClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + request = request_type() + request = json_format.ParseDict({"name": "sample1"}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_operation(request) + + +@pytest.mark.parametrize( + "request_type", + [ + operations_pb2.GetOperationRequest, + dict, + ], +) +def test_get_operation_rest(request_type): + client = AdaptationClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request_init = {"name": "sample1"} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation() + + # 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 + + response = client.get_operation(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.Operation) + + +def test_list_operations_rest_bad_request( + transport: str = "rest", request_type=operations_pb2.ListOperationsRequest +): + client = AdaptationClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + request = request_type() + request = json_format.ParseDict({}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_operations(request) + + +@pytest.mark.parametrize( + "request_type", + [ + operations_pb2.ListOperationsRequest, + dict, + ], +) +def test_list_operations_rest(request_type): + client = AdaptationClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request_init = {} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.ListOperationsResponse() + + # 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 + + response = client.list_operations(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.ListOperationsResponse) + + def test_get_operation(transport: str = "grpc"): client = AdaptationClient( credentials=ga_credentials.AnonymousCredentials(), @@ -4489,6 +7589,7 @@ async def test_list_operations_from_dict_async(): def test_transport_close(): transports = { + "rest": "_session", "grpc": "_grpc_channel", } @@ -4506,6 +7607,7 @@ def test_transport_close(): def test_client_ctx(): transports = [ + "rest", "grpc", ] for transport in transports: diff --git a/tests/unit/gapic/speech_v1/test_speech.py b/tests/unit/gapic/speech_v1/test_speech.py index 2f5bdf09..2811c837 100644 --- a/tests/unit/gapic/speech_v1/test_speech.py +++ b/tests/unit/gapic/speech_v1/test_speech.py @@ -24,10 +24,17 @@ import grpc from grpc.experimental import aio +from collections.abc import Iterable +from google.protobuf import json_format +import json import math import pytest from proto.marshal.rules.dates import DurationRule, TimestampRule from proto.marshal.rules import wrappers +from requests import Response +from requests import Request, PreparedRequest +from requests.sessions import Session +from google.protobuf import json_format from google.api_core import client_options from google.api_core import exceptions as core_exceptions @@ -97,6 +104,7 @@ def test__get_default_mtls_endpoint(): [ (SpeechClient, "grpc"), (SpeechAsyncClient, "grpc_asyncio"), + (SpeechClient, "rest"), ], ) def test_speech_client_from_service_account_info(client_class, transport_name): @@ -110,7 +118,11 @@ def test_speech_client_from_service_account_info(client_class, transport_name): assert client.transport._credentials == creds assert isinstance(client, client_class) - assert client.transport._host == ("speech.googleapis.com:443") + assert client.transport._host == ( + "speech.googleapis.com:443" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://speech.googleapis.com" + ) @pytest.mark.parametrize( @@ -118,6 +130,7 @@ def test_speech_client_from_service_account_info(client_class, transport_name): [ (transports.SpeechGrpcTransport, "grpc"), (transports.SpeechGrpcAsyncIOTransport, "grpc_asyncio"), + (transports.SpeechRestTransport, "rest"), ], ) def test_speech_client_service_account_always_use_jwt(transport_class, transport_name): @@ -141,6 +154,7 @@ def test_speech_client_service_account_always_use_jwt(transport_class, transport [ (SpeechClient, "grpc"), (SpeechAsyncClient, "grpc_asyncio"), + (SpeechClient, "rest"), ], ) def test_speech_client_from_service_account_file(client_class, transport_name): @@ -161,13 +175,18 @@ def test_speech_client_from_service_account_file(client_class, transport_name): assert client.transport._credentials == creds assert isinstance(client, client_class) - assert client.transport._host == ("speech.googleapis.com:443") + assert client.transport._host == ( + "speech.googleapis.com:443" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://speech.googleapis.com" + ) def test_speech_client_get_transport_class(): transport = SpeechClient.get_transport_class() available_transports = [ transports.SpeechGrpcTransport, + transports.SpeechRestTransport, ] assert transport in available_transports @@ -180,6 +199,7 @@ def test_speech_client_get_transport_class(): [ (SpeechClient, transports.SpeechGrpcTransport, "grpc"), (SpeechAsyncClient, transports.SpeechGrpcAsyncIOTransport, "grpc_asyncio"), + (SpeechClient, transports.SpeechRestTransport, "rest"), ], ) @mock.patch.object( @@ -319,6 +339,8 @@ def test_speech_client_client_options(client_class, transport_class, transport_n "grpc_asyncio", "false", ), + (SpeechClient, transports.SpeechRestTransport, "rest", "true"), + (SpeechClient, transports.SpeechRestTransport, "rest", "false"), ], ) @mock.patch.object( @@ -504,6 +526,7 @@ def test_speech_client_get_mtls_endpoint_and_cert_source(client_class): [ (SpeechClient, transports.SpeechGrpcTransport, "grpc"), (SpeechAsyncClient, transports.SpeechGrpcAsyncIOTransport, "grpc_asyncio"), + (SpeechClient, transports.SpeechRestTransport, "rest"), ], ) def test_speech_client_client_options_scopes( @@ -539,6 +562,7 @@ def test_speech_client_client_options_scopes( "grpc_asyncio", grpc_helpers_async, ), + (SpeechClient, transports.SpeechRestTransport, "rest", None), ], ) def test_speech_client_client_options_credentials_file( @@ -1111,6 +1135,569 @@ async def test_streaming_recognize_async_from_dict(): await test_streaming_recognize_async(request_type=dict) +@pytest.mark.parametrize( + "request_type", + [ + cloud_speech.RecognizeRequest, + dict, + ], +) +def test_recognize_rest(request_type): + client = SpeechClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = cloud_speech.RecognizeResponse( + request_id=1077, + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = cloud_speech.RecognizeResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.recognize(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, cloud_speech.RecognizeResponse) + assert response.request_id == 1077 + + +def test_recognize_rest_required_fields(request_type=cloud_speech.RecognizeRequest): + transport_class = transports.SpeechRestTransport + + request_init = {} + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False, + ) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).recognize._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).recognize._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + + client = SpeechClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = cloud_speech.RecognizeResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force 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 + + pb_return_value = cloud_speech.RecognizeResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.recognize(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_recognize_rest_unset_required_fields(): + transport = transports.SpeechRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.recognize._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(()) + & set( + ( + "config", + "audio", + ) + ) + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_recognize_rest_interceptors(null_interceptor): + transport = transports.SpeechRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SpeechRestInterceptor(), + ) + client = SpeechClient(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.SpeechRestInterceptor, "post_recognize" + ) as post, mock.patch.object( + transports.SpeechRestInterceptor, "pre_recognize" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = cloud_speech.RecognizeRequest.pb(cloud_speech.RecognizeRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = cloud_speech.RecognizeResponse.to_json( + cloud_speech.RecognizeResponse() + ) + + request = cloud_speech.RecognizeRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = cloud_speech.RecognizeResponse() + + client.recognize( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_recognize_rest_bad_request( + transport: str = "rest", request_type=cloud_speech.RecognizeRequest +): + client = SpeechClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.recognize(request) + + +def test_recognize_rest_flattened(): + client = SpeechClient( + 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 = cloud_speech.RecognizeResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {} + + # get truthy value for each flattened field + mock_args = dict( + config=cloud_speech.RecognitionConfig( + encoding=cloud_speech.RecognitionConfig.AudioEncoding.LINEAR16 + ), + audio=cloud_speech.RecognitionAudio(content=b"content_blob"), + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = cloud_speech.RecognizeResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.recognize(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1/speech:recognize" % client.transport._host, args[1] + ) + + +def test_recognize_rest_flattened_error(transport: str = "rest"): + client = SpeechClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.recognize( + cloud_speech.RecognizeRequest(), + config=cloud_speech.RecognitionConfig( + encoding=cloud_speech.RecognitionConfig.AudioEncoding.LINEAR16 + ), + audio=cloud_speech.RecognitionAudio(content=b"content_blob"), + ) + + +def test_recognize_rest_error(): + client = SpeechClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + cloud_speech.LongRunningRecognizeRequest, + dict, + ], +) +def test_long_running_recognize_rest(request_type): + client = SpeechClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # 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 + response = client.long_running_recognize(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_long_running_recognize_rest_required_fields( + request_type=cloud_speech.LongRunningRecognizeRequest, +): + transport_class = transports.SpeechRestTransport + + request_init = {} + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False, + ) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).long_running_recognize._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).long_running_recognize._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + + client = SpeechClient( + 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 + + response = client.long_running_recognize(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_long_running_recognize_rest_unset_required_fields(): + transport = transports.SpeechRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.long_running_recognize._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(()) + & set( + ( + "config", + "audio", + ) + ) + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_long_running_recognize_rest_interceptors(null_interceptor): + transport = transports.SpeechRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SpeechRestInterceptor(), + ) + client = SpeechClient(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.SpeechRestInterceptor, "post_long_running_recognize" + ) as post, mock.patch.object( + transports.SpeechRestInterceptor, "pre_long_running_recognize" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = cloud_speech.LongRunningRecognizeRequest.pb( + cloud_speech.LongRunningRecognizeRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson( + operations_pb2.Operation() + ) + + request = cloud_speech.LongRunningRecognizeRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.long_running_recognize( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_long_running_recognize_rest_bad_request( + transport: str = "rest", request_type=cloud_speech.LongRunningRecognizeRequest +): + client = SpeechClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.long_running_recognize(request) + + +def test_long_running_recognize_rest_flattened(): + client = SpeechClient( + 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 = {} + + # get truthy value for each flattened field + mock_args = dict( + config=cloud_speech.RecognitionConfig( + encoding=cloud_speech.RecognitionConfig.AudioEncoding.LINEAR16 + ), + audio=cloud_speech.RecognitionAudio(content=b"content_blob"), + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.long_running_recognize(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1/speech:longrunningrecognize" % client.transport._host, args[1] + ) + + +def test_long_running_recognize_rest_flattened_error(transport: str = "rest"): + client = SpeechClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.long_running_recognize( + cloud_speech.LongRunningRecognizeRequest(), + config=cloud_speech.RecognitionConfig( + encoding=cloud_speech.RecognitionConfig.AudioEncoding.LINEAR16 + ), + audio=cloud_speech.RecognitionAudio(content=b"content_blob"), + ) + + +def test_long_running_recognize_rest_error(): + client = SpeechClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +def test_streaming_recognize_rest_no_http_options(): + client = SpeechClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = cloud_speech.StreamingRecognizeRequest() + requests = [request] + with pytest.raises(RuntimeError): + client.streaming_recognize(requests) + + +def test_streaming_recognize_rest_error(): + client = SpeechClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # Since a `google.api.http` annotation is required for using a rest transport + # method, this should error. + with pytest.raises(NotImplementedError) as not_implemented_error: + client.streaming_recognize({}) + assert "Method StreamingRecognize is not available over REST transport" in str( + not_implemented_error.value + ) + + def test_credentials_transport_error(): # It is an error to provide credentials and a transport instance. transport = transports.SpeechGrpcTransport( @@ -1192,6 +1779,7 @@ def test_transport_get_channel(): [ transports.SpeechGrpcTransport, transports.SpeechGrpcAsyncIOTransport, + transports.SpeechRestTransport, ], ) def test_transport_adc(transport_class): @@ -1206,6 +1794,7 @@ def test_transport_adc(transport_class): "transport_name", [ "grpc", + "rest", ], ) def test_transport_kind(transport_name): @@ -1344,6 +1933,7 @@ def test_speech_transport_auth_adc(transport_class): [ transports.SpeechGrpcTransport, transports.SpeechGrpcAsyncIOTransport, + transports.SpeechRestTransport, ], ) def test_speech_transport_auth_gdch_credentials(transport_class): @@ -1438,11 +2028,40 @@ def test_speech_grpc_transport_client_cert_source_for_mtls(transport_class): ) +def test_speech_http_transport_client_cert_source_for_mtls(): + cred = ga_credentials.AnonymousCredentials() + with mock.patch( + "google.auth.transport.requests.AuthorizedSession.configure_mtls_channel" + ) as mock_configure_mtls_channel: + transports.SpeechRestTransport( + credentials=cred, client_cert_source_for_mtls=client_cert_source_callback + ) + mock_configure_mtls_channel.assert_called_once_with(client_cert_source_callback) + + +def test_speech_rest_lro_client(): + client = SpeechClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + transport = client.transport + + # Ensure that we have a api-core operations client. + assert isinstance( + transport.operations_client, + operations_v1.AbstractOperationsClient, + ) + + # Ensure that subsequent calls to the property send the exact same object. + assert transport.operations_client is transport.operations_client + + @pytest.mark.parametrize( "transport_name", [ "grpc", "grpc_asyncio", + "rest", ], ) def test_speech_host_no_port(transport_name): @@ -1453,7 +2072,11 @@ def test_speech_host_no_port(transport_name): ), transport=transport_name, ) - assert client.transport._host == ("speech.googleapis.com:443") + assert client.transport._host == ( + "speech.googleapis.com:443" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://speech.googleapis.com" + ) @pytest.mark.parametrize( @@ -1461,6 +2084,7 @@ def test_speech_host_no_port(transport_name): [ "grpc", "grpc_asyncio", + "rest", ], ) def test_speech_host_with_port(transport_name): @@ -1471,7 +2095,39 @@ def test_speech_host_with_port(transport_name): ), transport=transport_name, ) - assert client.transport._host == ("speech.googleapis.com:8000") + assert client.transport._host == ( + "speech.googleapis.com:8000" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://speech.googleapis.com:8000" + ) + + +@pytest.mark.parametrize( + "transport_name", + [ + "rest", + ], +) +def test_speech_client_transport_session_collision(transport_name): + creds1 = ga_credentials.AnonymousCredentials() + creds2 = ga_credentials.AnonymousCredentials() + client1 = SpeechClient( + credentials=creds1, + transport=transport_name, + ) + client2 = SpeechClient( + credentials=creds2, + transport=transport_name, + ) + session1 = client1.transport.recognize._session + session2 = client2.transport.recognize._session + assert session1 != session2 + session1 = client1.transport.long_running_recognize._session + session2 = client2.transport.long_running_recognize._session + assert session1 != session2 + session1 = client1.transport.streaming_recognize._session + session2 = client2.transport.streaming_recognize._session + assert session1 != session2 def test_speech_grpc_transport_channel(): @@ -1820,6 +2476,118 @@ async def test_transport_close_async(): close.assert_called_once() +def test_get_operation_rest_bad_request( + transport: str = "rest", request_type=operations_pb2.GetOperationRequest +): + client = SpeechClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + request = request_type() + request = json_format.ParseDict({"name": "sample1"}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_operation(request) + + +@pytest.mark.parametrize( + "request_type", + [ + operations_pb2.GetOperationRequest, + dict, + ], +) +def test_get_operation_rest(request_type): + client = SpeechClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request_init = {"name": "sample1"} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation() + + # 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 + + response = client.get_operation(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.Operation) + + +def test_list_operations_rest_bad_request( + transport: str = "rest", request_type=operations_pb2.ListOperationsRequest +): + client = SpeechClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + request = request_type() + request = json_format.ParseDict({}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_operations(request) + + +@pytest.mark.parametrize( + "request_type", + [ + operations_pb2.ListOperationsRequest, + dict, + ], +) +def test_list_operations_rest(request_type): + client = SpeechClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request_init = {} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.ListOperationsResponse() + + # 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 + + response = client.list_operations(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.ListOperationsResponse) + + def test_get_operation(transport: str = "grpc"): client = SpeechClient( credentials=ga_credentials.AnonymousCredentials(), @@ -2112,6 +2880,7 @@ async def test_list_operations_from_dict_async(): def test_transport_close(): transports = { + "rest": "_session", "grpc": "_grpc_channel", } @@ -2129,6 +2898,7 @@ def test_transport_close(): def test_client_ctx(): transports = [ + "rest", "grpc", ] for transport in transports: diff --git a/tests/unit/gapic/speech_v1p1beta1/test_adaptation.py b/tests/unit/gapic/speech_v1p1beta1/test_adaptation.py index a5825141..0df6fd9d 100644 --- a/tests/unit/gapic/speech_v1p1beta1/test_adaptation.py +++ b/tests/unit/gapic/speech_v1p1beta1/test_adaptation.py @@ -24,10 +24,17 @@ import grpc from grpc.experimental import aio +from collections.abc import Iterable +from google.protobuf import json_format +import json import math import pytest from proto.marshal.rules.dates import DurationRule, TimestampRule from proto.marshal.rules import wrappers +from requests import Response +from requests import Request, PreparedRequest +from requests.sessions import Session +from google.protobuf import json_format from google.api_core import client_options from google.api_core import exceptions as core_exceptions @@ -43,6 +50,7 @@ from google.cloud.speech_v1p1beta1.services.adaptation import transports from google.cloud.speech_v1p1beta1.types import cloud_speech_adaptation from google.cloud.speech_v1p1beta1.types import resource +from google.longrunning import operations_pb2 from google.oauth2 import service_account from google.protobuf import field_mask_pb2 # type: ignore import google.auth @@ -94,6 +102,7 @@ def test__get_default_mtls_endpoint(): [ (AdaptationClient, "grpc"), (AdaptationAsyncClient, "grpc_asyncio"), + (AdaptationClient, "rest"), ], ) def test_adaptation_client_from_service_account_info(client_class, transport_name): @@ -107,7 +116,11 @@ def test_adaptation_client_from_service_account_info(client_class, transport_nam assert client.transport._credentials == creds assert isinstance(client, client_class) - assert client.transport._host == ("speech.googleapis.com:443") + assert client.transport._host == ( + "speech.googleapis.com:443" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://speech.googleapis.com" + ) @pytest.mark.parametrize( @@ -115,6 +128,7 @@ def test_adaptation_client_from_service_account_info(client_class, transport_nam [ (transports.AdaptationGrpcTransport, "grpc"), (transports.AdaptationGrpcAsyncIOTransport, "grpc_asyncio"), + (transports.AdaptationRestTransport, "rest"), ], ) def test_adaptation_client_service_account_always_use_jwt( @@ -140,6 +154,7 @@ def test_adaptation_client_service_account_always_use_jwt( [ (AdaptationClient, "grpc"), (AdaptationAsyncClient, "grpc_asyncio"), + (AdaptationClient, "rest"), ], ) def test_adaptation_client_from_service_account_file(client_class, transport_name): @@ -160,13 +175,18 @@ def test_adaptation_client_from_service_account_file(client_class, transport_nam assert client.transport._credentials == creds assert isinstance(client, client_class) - assert client.transport._host == ("speech.googleapis.com:443") + assert client.transport._host == ( + "speech.googleapis.com:443" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://speech.googleapis.com" + ) def test_adaptation_client_get_transport_class(): transport = AdaptationClient.get_transport_class() available_transports = [ transports.AdaptationGrpcTransport, + transports.AdaptationRestTransport, ] assert transport in available_transports @@ -183,6 +203,7 @@ def test_adaptation_client_get_transport_class(): transports.AdaptationGrpcAsyncIOTransport, "grpc_asyncio", ), + (AdaptationClient, transports.AdaptationRestTransport, "rest"), ], ) @mock.patch.object( @@ -326,6 +347,8 @@ def test_adaptation_client_client_options( "grpc_asyncio", "false", ), + (AdaptationClient, transports.AdaptationRestTransport, "rest", "true"), + (AdaptationClient, transports.AdaptationRestTransport, "rest", "false"), ], ) @mock.patch.object( @@ -519,6 +542,7 @@ def test_adaptation_client_get_mtls_endpoint_and_cert_source(client_class): transports.AdaptationGrpcAsyncIOTransport, "grpc_asyncio", ), + (AdaptationClient, transports.AdaptationRestTransport, "rest"), ], ) def test_adaptation_client_client_options_scopes( @@ -554,6 +578,7 @@ def test_adaptation_client_client_options_scopes( "grpc_asyncio", grpc_helpers_async, ), + (AdaptationClient, transports.AdaptationRestTransport, "rest", None), ], ) def test_adaptation_client_client_options_credentials_file( @@ -3519,683 +3544,4056 @@ async def test_delete_custom_class_flattened_error_async(): ) -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.AdaptationGrpcTransport( +@pytest.mark.parametrize( + "request_type", + [ + cloud_speech_adaptation.CreatePhraseSetRequest, + dict, + ], +) +def test_create_phrase_set_rest(request_type): + client = AdaptationClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - with pytest.raises(ValueError): - client = AdaptationClient( - 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 response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = resource.PhraseSet( + name="name_value", + boost=0.551, ) - # It is an error to provide a credentials file and a transport instance. - transport = transports.AdaptationGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = AdaptationClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = resource.PhraseSet.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.create_phrase_set(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, resource.PhraseSet) + assert response.name == "name_value" + assert math.isclose(response.boost, 0.551, rel_tol=1e-6) + + +def test_create_phrase_set_rest_required_fields( + request_type=cloud_speech_adaptation.CreatePhraseSetRequest, +): + transport_class = transports.AdaptationRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["phrase_set_id"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False, ) + ) - # It is an error to provide an api_key and a transport instance. - transport = transports.AdaptationGrpcTransport( + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).create_phrase_set._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["phraseSetId"] = "phrase_set_id_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).create_phrase_set._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 "phraseSetId" in jsonified_request + assert jsonified_request["phraseSetId"] == "phrase_set_id_value" + + client = AdaptationClient( credentials=ga_credentials.AnonymousCredentials(), - ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = AdaptationClient( - client_options=options, - transport=transport, + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = resource.PhraseSet() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force 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 + + pb_return_value = resource.PhraseSet.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.create_phrase_set(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_create_phrase_set_rest_unset_required_fields(): + transport = transports.AdaptationRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.create_phrase_set._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(()) + & set( + ( + "parent", + "phraseSetId", + "phraseSet", + ) ) + ) - # It is an error to provide an api_key and a credential. - options = mock.Mock() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = AdaptationClient( - client_options=options, credentials=ga_credentials.AnonymousCredentials() - ) - # It is an error to provide scopes and a transport instance. - transport = transports.AdaptationGrpcTransport( +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_phrase_set_rest_interceptors(null_interceptor): + transport = transports.AdaptationRestTransport( credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.AdaptationRestInterceptor(), ) - with pytest.raises(ValueError): - client = AdaptationClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, + client = AdaptationClient(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.AdaptationRestInterceptor, "post_create_phrase_set" + ) as post, mock.patch.object( + transports.AdaptationRestInterceptor, "pre_create_phrase_set" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = cloud_speech_adaptation.CreatePhraseSetRequest.pb( + cloud_speech_adaptation.CreatePhraseSetRequest() ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = resource.PhraseSet.to_json(resource.PhraseSet()) + + request = cloud_speech_adaptation.CreatePhraseSetRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = resource.PhraseSet() + client.create_phrase_set( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.AdaptationGrpcTransport( + pre.assert_called_once() + post.assert_called_once() + + +def test_create_phrase_set_rest_bad_request( + transport: str = "rest", request_type=cloud_speech_adaptation.CreatePhraseSetRequest +): + client = AdaptationClient( credentials=ga_credentials.AnonymousCredentials(), + transport=transport, ) - client = AdaptationClient(transport=transport) - assert client.transport is transport + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2"} + request = request_type(**request_init) -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.AdaptationGrpcTransport( + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.create_phrase_set(request) + + +def test_create_phrase_set_rest_flattened(): + client = AdaptationClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - channel = transport.grpc_channel - assert channel - transport = transports.AdaptationGrpcAsyncIOTransport( + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = resource.PhraseSet() + + # 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", + phrase_set=resource.PhraseSet(name="name_value"), + phrase_set_id="phrase_set_id_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = resource.PhraseSet.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.create_phrase_set(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1p1beta1/{parent=projects/*/locations/*}/phraseSets" + % client.transport._host, + args[1], + ) + + +def test_create_phrase_set_rest_flattened_error(transport: str = "rest"): + client = AdaptationClient( credentials=ga_credentials.AnonymousCredentials(), + transport=transport, ) - channel = transport.grpc_channel - assert channel + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.create_phrase_set( + cloud_speech_adaptation.CreatePhraseSetRequest(), + parent="parent_value", + phrase_set=resource.PhraseSet(name="name_value"), + phrase_set_id="phrase_set_id_value", + ) -@pytest.mark.parametrize( - "transport_class", - [ - transports.AdaptationGrpcTransport, - transports.AdaptationGrpcAsyncIOTransport, - ], -) -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_create_phrase_set_rest_error(): + client = AdaptationClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) @pytest.mark.parametrize( - "transport_name", + "request_type", [ - "grpc", + cloud_speech_adaptation.GetPhraseSetRequest, + dict, ], ) -def test_transport_kind(transport_name): - transport = AdaptationClient.get_transport_class(transport_name)( +def test_get_phrase_set_rest(request_type): + client = AdaptationClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - assert transport.kind == transport_name + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/phraseSets/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 = resource.PhraseSet( + name="name_value", + boost=0.551, + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = resource.PhraseSet.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.get_phrase_set(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, resource.PhraseSet) + assert response.name == "name_value" + assert math.isclose(response.boost, 0.551, rel_tol=1e-6) + + +def test_get_phrase_set_rest_required_fields( + request_type=cloud_speech_adaptation.GetPhraseSetRequest, +): + transport_class = transports.AdaptationRestTransport + + 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, + including_default_value_fields=False, + use_integers_for_enums=False, + ) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get_phrase_set._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_phrase_set._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" -def test_transport_grpc_default(): - # A client should use the gRPC transport by default. client = AdaptationClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - assert isinstance( - client.transport, - transports.AdaptationGrpcTransport, - ) + request = request_type(**request_init) + # Designate an appropriate value for the returned response. + return_value = resource.PhraseSet() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force 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 -def test_adaptation_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.AdaptationTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json", - ) + response_value = Response() + response_value.status_code = 200 + pb_return_value = resource.PhraseSet.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) -def test_adaptation_base_transport(): - # Instantiate the base transport. - with mock.patch( - "google.cloud.speech_v1p1beta1.services.adaptation.transports.AdaptationTransport.__init__" - ) as Transport: - Transport.return_value = None - transport = transports.AdaptationTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - "create_phrase_set", - "get_phrase_set", - "list_phrase_set", - "update_phrase_set", - "delete_phrase_set", - "create_custom_class", - "get_custom_class", - "list_custom_classes", - "update_custom_class", - "delete_custom_class", - ) - for method in methods: - with pytest.raises(NotImplementedError): - getattr(transport, method)(request=object()) + response = client.get_phrase_set(request) - with pytest.raises(NotImplementedError): - transport.close() + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params - # Catch all for all remaining methods and properties - remainder = [ - "kind", - ] - for r in remainder: - with pytest.raises(NotImplementedError): - getattr(transport, r)() +def test_get_phrase_set_rest_unset_required_fields(): + transport = transports.AdaptationRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) -def test_adaptation_base_transport_with_credentials_file(): - # Instantiate the base transport with a credentials file + unset_fields = transport.get_phrase_set._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_phrase_set_rest_interceptors(null_interceptor): + transport = transports.AdaptationRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.AdaptationRestInterceptor(), + ) + client = AdaptationClient(transport=transport) with mock.patch.object( - google.auth, "load_credentials_from_file", autospec=True - ) as load_creds, mock.patch( - "google.cloud.speech_v1p1beta1.services.adaptation.transports.AdaptationTransport._prep_wrapped_messages" - ) as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.AdaptationTransport( - credentials_file="credentials.json", - quota_project_id="octopus", + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.AdaptationRestInterceptor, "post_get_phrase_set" + ) as post, mock.patch.object( + transports.AdaptationRestInterceptor, "pre_get_phrase_set" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = cloud_speech_adaptation.GetPhraseSetRequest.pb( + cloud_speech_adaptation.GetPhraseSetRequest() ) - load_creds.assert_called_once_with( - "credentials.json", - scopes=None, - default_scopes=("https://www.googleapis.com/auth/cloud-platform",), - quota_project_id="octopus", + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = resource.PhraseSet.to_json(resource.PhraseSet()) + + request = cloud_speech_adaptation.GetPhraseSetRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = resource.PhraseSet() + + client.get_phrase_set( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], ) + pre.assert_called_once() + post.assert_called_once() -def test_adaptation_base_transport_with_adc(): - # Test the default credentials are used if credentials and credentials_file are None. - with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch( - "google.cloud.speech_v1p1beta1.services.adaptation.transports.AdaptationTransport._prep_wrapped_messages" - ) as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.AdaptationTransport() - adc.assert_called_once() +def test_get_phrase_set_rest_bad_request( + transport: str = "rest", request_type=cloud_speech_adaptation.GetPhraseSetRequest +): + client = AdaptationClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) -def test_adaptation_auth_adc(): - # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(google.auth, "default", autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - AdaptationClient() - adc.assert_called_once_with( - scopes=None, - default_scopes=("https://www.googleapis.com/auth/cloud-platform",), - quota_project_id=None, - ) - + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/phraseSets/sample3"} + request = request_type(**request_init) -@pytest.mark.parametrize( - "transport_class", - [ - transports.AdaptationGrpcTransport, - transports.AdaptationGrpcAsyncIOTransport, - ], -) -def test_adaptation_transport_auth_adc(transport_class): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, "default", autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class(quota_project_id="octopus", scopes=["1", "2"]) - adc.assert_called_once_with( - scopes=["1", "2"], - default_scopes=("https://www.googleapis.com/auth/cloud-platform",), - quota_project_id="octopus", - ) + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_phrase_set(request) -@pytest.mark.parametrize( - "transport_class", - [ - transports.AdaptationGrpcTransport, - transports.AdaptationGrpcAsyncIOTransport, - ], -) -def test_adaptation_transport_auth_gdch_credentials(transport_class): - host = "https://language.com" - api_audience_tests = [None, "https://language2.com"] - api_audience_expect = [host, "https://language2.com"] - for t, e in zip(api_audience_tests, api_audience_expect): - with mock.patch.object(google.auth, "default", autospec=True) as adc: - gdch_mock = mock.MagicMock() - type(gdch_mock).with_gdch_audience = mock.PropertyMock( - return_value=gdch_mock - ) - adc.return_value = (gdch_mock, None) - transport_class(host=host, api_audience=t) - gdch_mock.with_gdch_audience.assert_called_once_with(e) +def test_get_phrase_set_rest_flattened(): + client = AdaptationClient( + 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 = resource.PhraseSet() -@pytest.mark.parametrize( - "transport_class,grpc_helpers", - [ - (transports.AdaptationGrpcTransport, grpc_helpers), - (transports.AdaptationGrpcAsyncIOTransport, grpc_helpers_async), - ], -) -def test_adaptation_transport_create_channel(transport_class, grpc_helpers): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object( - google.auth, "default", autospec=True - ) as adc, mock.patch.object( - grpc_helpers, "create_channel", autospec=True - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - adc.return_value = (creds, None) - transport_class(quota_project_id="octopus", scopes=["1", "2"]) + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/phraseSets/sample3" + } - create_channel.assert_called_with( - "speech.googleapis.com:443", - credentials=creds, - credentials_file=None, - quota_project_id="octopus", - default_scopes=("https://www.googleapis.com/auth/cloud-platform",), - scopes=["1", "2"], - default_host="speech.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], + # 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 + pb_return_value = resource.PhraseSet.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value -@pytest.mark.parametrize( - "transport_class", - [transports.AdaptationGrpcTransport, transports.AdaptationGrpcAsyncIOTransport], -) -def test_adaptation_grpc_transport_client_cert_source_for_mtls(transport_class): - cred = ga_credentials.AnonymousCredentials() + client.get_phrase_set(**mock_args) - # Check ssl_channel_credentials is used if provided. - with mock.patch.object(transport_class, "create_channel") as mock_create_channel: - mock_ssl_channel_creds = mock.Mock() - transport_class( - host="squid.clam.whelk", - credentials=cred, - ssl_channel_credentials=mock_ssl_channel_creds, - ) - mock_create_channel.assert_called_once_with( - "squid.clam.whelk:443", - credentials=cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_channel_creds, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1p1beta1/{name=projects/*/locations/*/phraseSets/*}" + % client.transport._host, + args[1], ) - # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls - # is used. - with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): - with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: - transport_class( - credentials=cred, - client_cert_source_for_mtls=client_cert_source_callback, - ) - expected_cert, expected_key = client_cert_source_callback() - mock_ssl_cred.assert_called_once_with( - certificate_chain=expected_cert, private_key=expected_key - ) - -@pytest.mark.parametrize( - "transport_name", - [ - "grpc", - "grpc_asyncio", - ], -) -def test_adaptation_host_no_port(transport_name): +def test_get_phrase_set_rest_flattened_error(transport: str = "rest"): client = AdaptationClient( credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions( - api_endpoint="speech.googleapis.com" - ), - transport=transport_name, + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_phrase_set( + cloud_speech_adaptation.GetPhraseSetRequest(), + name="name_value", + ) + + +def test_get_phrase_set_rest_error(): + client = AdaptationClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) - assert client.transport._host == ("speech.googleapis.com:443") @pytest.mark.parametrize( - "transport_name", + "request_type", [ - "grpc", - "grpc_asyncio", + cloud_speech_adaptation.ListPhraseSetRequest, + dict, ], ) -def test_adaptation_host_with_port(transport_name): +def test_list_phrase_set_rest(request_type): client = AdaptationClient( credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions( - api_endpoint="speech.googleapis.com:8000" - ), - transport=transport_name, + transport="rest", ) - assert client.transport._host == ("speech.googleapis.com:8000") + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2"} + request = request_type(**request_init) -def test_adaptation_grpc_transport_channel(): - channel = grpc.secure_channel("http://localhost/", grpc.local_channel_credentials()) + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = cloud_speech_adaptation.ListPhraseSetResponse( + next_page_token="next_page_token_value", + ) - # Check that channel is used if provided. - transport = transports.AdaptationGrpcTransport( - host="squid.clam.whelk", - channel=channel, - ) - assert transport.grpc_channel == channel - assert transport._host == "squid.clam.whelk:443" - assert transport._ssl_channel_credentials == None + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = cloud_speech_adaptation.ListPhraseSetResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.list_phrase_set(request) -def test_adaptation_grpc_asyncio_transport_channel(): - channel = aio.secure_channel("http://localhost/", grpc.local_channel_credentials()) + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListPhraseSetPager) + assert response.next_page_token == "next_page_token_value" - # Check that channel is used if provided. - transport = transports.AdaptationGrpcAsyncIOTransport( - host="squid.clam.whelk", - channel=channel, + +def test_list_phrase_set_rest_required_fields( + request_type=cloud_speech_adaptation.ListPhraseSetRequest, +): + transport_class = transports.AdaptationRestTransport + + 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, + including_default_value_fields=False, + use_integers_for_enums=False, + ) ) - assert transport.grpc_channel == channel - assert transport._host == "squid.clam.whelk:443" - assert transport._ssl_channel_credentials == None + # verify fields with default values are dropped -# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are -# removed from grpc/grpc_asyncio transport constructor. -@pytest.mark.parametrize( - "transport_class", - [transports.AdaptationGrpcTransport, transports.AdaptationGrpcAsyncIOTransport], -) -def test_adaptation_transport_channel_mtls_with_client_cert_source(transport_class): - with mock.patch( - "grpc.ssl_channel_credentials", autospec=True - ) as grpc_ssl_channel_cred: - with mock.patch.object( - transport_class, "create_channel" - ) as grpc_create_channel: - mock_ssl_cred = mock.Mock() - grpc_ssl_channel_cred.return_value = mock_ssl_cred + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).list_phrase_set._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) - mock_grpc_channel = mock.Mock() - grpc_create_channel.return_value = mock_grpc_channel + # verify required fields with default values are now present - cred = ga_credentials.AnonymousCredentials() - with pytest.warns(DeprecationWarning): - with mock.patch.object(google.auth, "default") as adc: - adc.return_value = (cred, None) - transport = transport_class( - host="squid.clam.whelk", - api_mtls_endpoint="mtls.squid.clam.whelk", - client_cert_source=client_cert_source_callback, - ) - adc.assert_called_once() + jsonified_request["parent"] = "parent_value" - grpc_ssl_channel_cred.assert_called_once_with( - certificate_chain=b"cert bytes", private_key=b"key bytes" + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).list_phrase_set._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "page_size", + "page_token", + ) + ) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + + client = AdaptationClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = cloud_speech_adaptation.ListPhraseSetResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force 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 + + pb_return_value = cloud_speech_adaptation.ListPhraseSetResponse.pb( + return_value ) - grpc_create_channel.assert_called_once_with( - "mtls.squid.clam.whelk:443", - credentials=cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_cred, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.list_phrase_set(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_list_phrase_set_rest_unset_required_fields(): + transport = transports.AdaptationRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.list_phrase_set._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "pageSize", + "pageToken", ) - assert transport.grpc_channel == mock_grpc_channel - assert transport._ssl_channel_credentials == mock_ssl_cred + ) + & set(("parent",)) + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_phrase_set_rest_interceptors(null_interceptor): + transport = transports.AdaptationRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.AdaptationRestInterceptor(), + ) + client = AdaptationClient(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.AdaptationRestInterceptor, "post_list_phrase_set" + ) as post, mock.patch.object( + transports.AdaptationRestInterceptor, "pre_list_phrase_set" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = cloud_speech_adaptation.ListPhraseSetRequest.pb( + cloud_speech_adaptation.ListPhraseSetRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = ( + cloud_speech_adaptation.ListPhraseSetResponse.to_json( + cloud_speech_adaptation.ListPhraseSetResponse() + ) + ) + + request = cloud_speech_adaptation.ListPhraseSetRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = cloud_speech_adaptation.ListPhraseSetResponse() + + client.list_phrase_set( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_phrase_set_rest_bad_request( + transport: str = "rest", request_type=cloud_speech_adaptation.ListPhraseSetRequest +): + client = AdaptationClient( + 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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_phrase_set(request) + + +def test_list_phrase_set_rest_flattened(): + client = AdaptationClient( + 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 = cloud_speech_adaptation.ListPhraseSetResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {"parent": "projects/sample1/locations/sample2"} + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = cloud_speech_adaptation.ListPhraseSetResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.list_phrase_set(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1p1beta1/{parent=projects/*/locations/*}/phraseSets" + % client.transport._host, + args[1], + ) + + +def test_list_phrase_set_rest_flattened_error(transport: str = "rest"): + client = AdaptationClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_phrase_set( + cloud_speech_adaptation.ListPhraseSetRequest(), + parent="parent_value", + ) + + +def test_list_phrase_set_rest_pager(transport: str = "rest"): + client = AdaptationClient( + 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 = ( + cloud_speech_adaptation.ListPhraseSetResponse( + phrase_sets=[ + resource.PhraseSet(), + resource.PhraseSet(), + resource.PhraseSet(), + ], + next_page_token="abc", + ), + cloud_speech_adaptation.ListPhraseSetResponse( + phrase_sets=[], + next_page_token="def", + ), + cloud_speech_adaptation.ListPhraseSetResponse( + phrase_sets=[ + resource.PhraseSet(), + ], + next_page_token="ghi", + ), + cloud_speech_adaptation.ListPhraseSetResponse( + phrase_sets=[ + resource.PhraseSet(), + resource.PhraseSet(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple( + cloud_speech_adaptation.ListPhraseSetResponse.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_phrase_set(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, resource.PhraseSet) for i in results) + + pages = list(client.list_phrase_set(request=sample_request).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.parametrize( + "request_type", + [ + cloud_speech_adaptation.UpdatePhraseSetRequest, + dict, + ], +) +def test_update_phrase_set_rest(request_type): + client = AdaptationClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = { + "phrase_set": {"name": "projects/sample1/locations/sample2/phraseSets/sample3"} + } + request_init["phrase_set"] = { + "name": "projects/sample1/locations/sample2/phraseSets/sample3", + "phrases": [{"value": "value_value", "boost": 0.551}], + "boost": 0.551, + } + 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 = resource.PhraseSet( + name="name_value", + boost=0.551, + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = resource.PhraseSet.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.update_phrase_set(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, resource.PhraseSet) + assert response.name == "name_value" + assert math.isclose(response.boost, 0.551, rel_tol=1e-6) + + +def test_update_phrase_set_rest_required_fields( + request_type=cloud_speech_adaptation.UpdatePhraseSetRequest, +): + transport_class = transports.AdaptationRestTransport + + request_init = {} + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False, + ) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).update_phrase_set._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).update_phrase_set._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("update_mask",)) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + + client = AdaptationClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = resource.PhraseSet() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "patch", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + pb_return_value = resource.PhraseSet.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.update_phrase_set(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_update_phrase_set_rest_unset_required_fields(): + transport = transports.AdaptationRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.update_phrase_set._get_unset_required_fields({}) + assert set(unset_fields) == (set(("updateMask",)) & set(("phraseSet",))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_phrase_set_rest_interceptors(null_interceptor): + transport = transports.AdaptationRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.AdaptationRestInterceptor(), + ) + client = AdaptationClient(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.AdaptationRestInterceptor, "post_update_phrase_set" + ) as post, mock.patch.object( + transports.AdaptationRestInterceptor, "pre_update_phrase_set" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = cloud_speech_adaptation.UpdatePhraseSetRequest.pb( + cloud_speech_adaptation.UpdatePhraseSetRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = resource.PhraseSet.to_json(resource.PhraseSet()) + + request = cloud_speech_adaptation.UpdatePhraseSetRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = resource.PhraseSet() + + client.update_phrase_set( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_phrase_set_rest_bad_request( + transport: str = "rest", request_type=cloud_speech_adaptation.UpdatePhraseSetRequest +): + client = AdaptationClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = { + "phrase_set": {"name": "projects/sample1/locations/sample2/phraseSets/sample3"} + } + request_init["phrase_set"] = { + "name": "projects/sample1/locations/sample2/phraseSets/sample3", + "phrases": [{"value": "value_value", "boost": 0.551}], + "boost": 0.551, + } + 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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.update_phrase_set(request) + + +def test_update_phrase_set_rest_flattened(): + client = AdaptationClient( + 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 = resource.PhraseSet() + + # get arguments that satisfy an http rule for this method + sample_request = { + "phrase_set": { + "name": "projects/sample1/locations/sample2/phraseSets/sample3" + } + } + + # get truthy value for each flattened field + mock_args = dict( + phrase_set=resource.PhraseSet(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 + pb_return_value = resource.PhraseSet.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.update_phrase_set(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1p1beta1/{phrase_set.name=projects/*/locations/*/phraseSets/*}" + % client.transport._host, + args[1], + ) + + +def test_update_phrase_set_rest_flattened_error(transport: str = "rest"): + client = AdaptationClient( + credentials=ga_credentials.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_phrase_set( + cloud_speech_adaptation.UpdatePhraseSetRequest(), + phrase_set=resource.PhraseSet(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +def test_update_phrase_set_rest_error(): + client = AdaptationClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + cloud_speech_adaptation.DeletePhraseSetRequest, + dict, + ], +) +def test_delete_phrase_set_rest(request_type): + client = AdaptationClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/phraseSets/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 = None + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = "" + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.delete_phrase_set(request) + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_phrase_set_rest_required_fields( + request_type=cloud_speech_adaptation.DeletePhraseSetRequest, +): + transport_class = transports.AdaptationRestTransport + + 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, + including_default_value_fields=False, + use_integers_for_enums=False, + ) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).delete_phrase_set._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_phrase_set._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 = AdaptationClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = None + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "delete", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = "" + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.delete_phrase_set(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_delete_phrase_set_rest_unset_required_fields(): + transport = transports.AdaptationRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.delete_phrase_set._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_phrase_set_rest_interceptors(null_interceptor): + transport = transports.AdaptationRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.AdaptationRestInterceptor(), + ) + client = AdaptationClient(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.AdaptationRestInterceptor, "pre_delete_phrase_set" + ) as pre: + pre.assert_not_called() + pb_message = cloud_speech_adaptation.DeletePhraseSetRequest.pb( + cloud_speech_adaptation.DeletePhraseSetRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + + request = cloud_speech_adaptation.DeletePhraseSetRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + + client.delete_phrase_set( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + + +def test_delete_phrase_set_rest_bad_request( + transport: str = "rest", request_type=cloud_speech_adaptation.DeletePhraseSetRequest +): + client = AdaptationClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/phraseSets/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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.delete_phrase_set(request) + + +def test_delete_phrase_set_rest_flattened(): + client = AdaptationClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = None + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/phraseSets/sample3" + } + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = "" + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.delete_phrase_set(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1p1beta1/{name=projects/*/locations/*/phraseSets/*}" + % client.transport._host, + args[1], + ) + + +def test_delete_phrase_set_rest_flattened_error(transport: str = "rest"): + client = AdaptationClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.delete_phrase_set( + cloud_speech_adaptation.DeletePhraseSetRequest(), + name="name_value", + ) + + +def test_delete_phrase_set_rest_error(): + client = AdaptationClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + cloud_speech_adaptation.CreateCustomClassRequest, + dict, + ], +) +def test_create_custom_class_rest(request_type): + client = AdaptationClient( + 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 = resource.CustomClass( + name="name_value", + custom_class_id="custom_class_id_value", + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = resource.CustomClass.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.create_custom_class(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, resource.CustomClass) + assert response.name == "name_value" + assert response.custom_class_id == "custom_class_id_value" + + +def test_create_custom_class_rest_required_fields( + request_type=cloud_speech_adaptation.CreateCustomClassRequest, +): + transport_class = transports.AdaptationRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["custom_class_id"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False, + ) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).create_custom_class._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["customClassId"] = "custom_class_id_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).create_custom_class._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 "customClassId" in jsonified_request + assert jsonified_request["customClassId"] == "custom_class_id_value" + + client = AdaptationClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = resource.CustomClass() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force 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 + + pb_return_value = resource.CustomClass.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.create_custom_class(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_create_custom_class_rest_unset_required_fields(): + transport = transports.AdaptationRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.create_custom_class._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(()) + & set( + ( + "parent", + "customClassId", + "customClass", + ) + ) + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_custom_class_rest_interceptors(null_interceptor): + transport = transports.AdaptationRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.AdaptationRestInterceptor(), + ) + client = AdaptationClient(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.AdaptationRestInterceptor, "post_create_custom_class" + ) as post, mock.patch.object( + transports.AdaptationRestInterceptor, "pre_create_custom_class" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = cloud_speech_adaptation.CreateCustomClassRequest.pb( + cloud_speech_adaptation.CreateCustomClassRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = resource.CustomClass.to_json(resource.CustomClass()) + + request = cloud_speech_adaptation.CreateCustomClassRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = resource.CustomClass() + + client.create_custom_class( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_create_custom_class_rest_bad_request( + transport: str = "rest", + request_type=cloud_speech_adaptation.CreateCustomClassRequest, +): + client = AdaptationClient( + 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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.create_custom_class(request) + + +def test_create_custom_class_rest_flattened(): + client = AdaptationClient( + 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 = resource.CustomClass() + + # 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", + custom_class=resource.CustomClass(name="name_value"), + custom_class_id="custom_class_id_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = resource.CustomClass.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.create_custom_class(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1p1beta1/{parent=projects/*/locations/*}/customClasses" + % client.transport._host, + args[1], + ) + + +def test_create_custom_class_rest_flattened_error(transport: str = "rest"): + client = AdaptationClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.create_custom_class( + cloud_speech_adaptation.CreateCustomClassRequest(), + parent="parent_value", + custom_class=resource.CustomClass(name="name_value"), + custom_class_id="custom_class_id_value", + ) + + +def test_create_custom_class_rest_error(): + client = AdaptationClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + cloud_speech_adaptation.GetCustomClassRequest, + dict, + ], +) +def test_get_custom_class_rest(request_type): + client = AdaptationClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/customClasses/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 = resource.CustomClass( + name="name_value", + custom_class_id="custom_class_id_value", + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = resource.CustomClass.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.get_custom_class(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, resource.CustomClass) + assert response.name == "name_value" + assert response.custom_class_id == "custom_class_id_value" + + +def test_get_custom_class_rest_required_fields( + request_type=cloud_speech_adaptation.GetCustomClassRequest, +): + transport_class = transports.AdaptationRestTransport + + 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, + including_default_value_fields=False, + use_integers_for_enums=False, + ) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get_custom_class._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_custom_class._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 = AdaptationClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = resource.CustomClass() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force 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 + + pb_return_value = resource.CustomClass.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.get_custom_class(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_get_custom_class_rest_unset_required_fields(): + transport = transports.AdaptationRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.get_custom_class._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_custom_class_rest_interceptors(null_interceptor): + transport = transports.AdaptationRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.AdaptationRestInterceptor(), + ) + client = AdaptationClient(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.AdaptationRestInterceptor, "post_get_custom_class" + ) as post, mock.patch.object( + transports.AdaptationRestInterceptor, "pre_get_custom_class" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = cloud_speech_adaptation.GetCustomClassRequest.pb( + cloud_speech_adaptation.GetCustomClassRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = resource.CustomClass.to_json(resource.CustomClass()) + + request = cloud_speech_adaptation.GetCustomClassRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = resource.CustomClass() + + client.get_custom_class( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_custom_class_rest_bad_request( + transport: str = "rest", request_type=cloud_speech_adaptation.GetCustomClassRequest +): + client = AdaptationClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/customClasses/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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_custom_class(request) + + +def test_get_custom_class_rest_flattened(): + client = AdaptationClient( + 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 = resource.CustomClass() + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/customClasses/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 + pb_return_value = resource.CustomClass.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.get_custom_class(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1p1beta1/{name=projects/*/locations/*/customClasses/*}" + % client.transport._host, + args[1], + ) + + +def test_get_custom_class_rest_flattened_error(transport: str = "rest"): + client = AdaptationClient( + credentials=ga_credentials.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_custom_class( + cloud_speech_adaptation.GetCustomClassRequest(), + name="name_value", + ) + + +def test_get_custom_class_rest_error(): + client = AdaptationClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + cloud_speech_adaptation.ListCustomClassesRequest, + dict, + ], +) +def test_list_custom_classes_rest(request_type): + client = AdaptationClient( + 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 = cloud_speech_adaptation.ListCustomClassesResponse( + next_page_token="next_page_token_value", + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = cloud_speech_adaptation.ListCustomClassesResponse.pb( + return_value + ) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.list_custom_classes(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListCustomClassesPager) + assert response.next_page_token == "next_page_token_value" + + +def test_list_custom_classes_rest_required_fields( + request_type=cloud_speech_adaptation.ListCustomClassesRequest, +): + transport_class = transports.AdaptationRestTransport + + 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, + including_default_value_fields=False, + use_integers_for_enums=False, + ) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).list_custom_classes._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = "parent_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).list_custom_classes._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "page_size", + "page_token", + ) + ) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + + client = AdaptationClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = cloud_speech_adaptation.ListCustomClassesResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force 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 + + pb_return_value = cloud_speech_adaptation.ListCustomClassesResponse.pb( + return_value + ) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.list_custom_classes(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_list_custom_classes_rest_unset_required_fields(): + transport = transports.AdaptationRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.list_custom_classes._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "pageSize", + "pageToken", + ) + ) + & set(("parent",)) + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_custom_classes_rest_interceptors(null_interceptor): + transport = transports.AdaptationRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.AdaptationRestInterceptor(), + ) + client = AdaptationClient(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.AdaptationRestInterceptor, "post_list_custom_classes" + ) as post, mock.patch.object( + transports.AdaptationRestInterceptor, "pre_list_custom_classes" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = cloud_speech_adaptation.ListCustomClassesRequest.pb( + cloud_speech_adaptation.ListCustomClassesRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = ( + cloud_speech_adaptation.ListCustomClassesResponse.to_json( + cloud_speech_adaptation.ListCustomClassesResponse() + ) + ) + + request = cloud_speech_adaptation.ListCustomClassesRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = cloud_speech_adaptation.ListCustomClassesResponse() + + client.list_custom_classes( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_custom_classes_rest_bad_request( + transport: str = "rest", + request_type=cloud_speech_adaptation.ListCustomClassesRequest, +): + client = AdaptationClient( + 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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_custom_classes(request) + + +def test_list_custom_classes_rest_flattened(): + client = AdaptationClient( + 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 = cloud_speech_adaptation.ListCustomClassesResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {"parent": "projects/sample1/locations/sample2"} + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = cloud_speech_adaptation.ListCustomClassesResponse.pb( + return_value + ) + json_return_value = json_format.MessageToJson(pb_return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.list_custom_classes(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1p1beta1/{parent=projects/*/locations/*}/customClasses" + % client.transport._host, + args[1], + ) + + +def test_list_custom_classes_rest_flattened_error(transport: str = "rest"): + client = AdaptationClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_custom_classes( + cloud_speech_adaptation.ListCustomClassesRequest(), + parent="parent_value", + ) + + +def test_list_custom_classes_rest_pager(transport: str = "rest"): + client = AdaptationClient( + 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 = ( + cloud_speech_adaptation.ListCustomClassesResponse( + custom_classes=[ + resource.CustomClass(), + resource.CustomClass(), + resource.CustomClass(), + ], + next_page_token="abc", + ), + cloud_speech_adaptation.ListCustomClassesResponse( + custom_classes=[], + next_page_token="def", + ), + cloud_speech_adaptation.ListCustomClassesResponse( + custom_classes=[ + resource.CustomClass(), + ], + next_page_token="ghi", + ), + cloud_speech_adaptation.ListCustomClassesResponse( + custom_classes=[ + resource.CustomClass(), + resource.CustomClass(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple( + cloud_speech_adaptation.ListCustomClassesResponse.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_custom_classes(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, resource.CustomClass) for i in results) + + pages = list(client.list_custom_classes(request=sample_request).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.parametrize( + "request_type", + [ + cloud_speech_adaptation.UpdateCustomClassRequest, + dict, + ], +) +def test_update_custom_class_rest(request_type): + client = AdaptationClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = { + "custom_class": { + "name": "projects/sample1/locations/sample2/customClasses/sample3" + } + } + request_init["custom_class"] = { + "name": "projects/sample1/locations/sample2/customClasses/sample3", + "custom_class_id": "custom_class_id_value", + "items": [{"value": "value_value"}], + } + 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 = resource.CustomClass( + name="name_value", + custom_class_id="custom_class_id_value", + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = resource.CustomClass.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.update_custom_class(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, resource.CustomClass) + assert response.name == "name_value" + assert response.custom_class_id == "custom_class_id_value" + + +def test_update_custom_class_rest_required_fields( + request_type=cloud_speech_adaptation.UpdateCustomClassRequest, +): + transport_class = transports.AdaptationRestTransport + + request_init = {} + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False, + ) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).update_custom_class._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).update_custom_class._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("update_mask",)) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + + client = AdaptationClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = resource.CustomClass() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "patch", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + pb_return_value = resource.CustomClass.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.update_custom_class(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_update_custom_class_rest_unset_required_fields(): + transport = transports.AdaptationRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.update_custom_class._get_unset_required_fields({}) + assert set(unset_fields) == (set(("updateMask",)) & set(("customClass",))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_custom_class_rest_interceptors(null_interceptor): + transport = transports.AdaptationRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.AdaptationRestInterceptor(), + ) + client = AdaptationClient(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.AdaptationRestInterceptor, "post_update_custom_class" + ) as post, mock.patch.object( + transports.AdaptationRestInterceptor, "pre_update_custom_class" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = cloud_speech_adaptation.UpdateCustomClassRequest.pb( + cloud_speech_adaptation.UpdateCustomClassRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = resource.CustomClass.to_json(resource.CustomClass()) + + request = cloud_speech_adaptation.UpdateCustomClassRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = resource.CustomClass() + + client.update_custom_class( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_custom_class_rest_bad_request( + transport: str = "rest", + request_type=cloud_speech_adaptation.UpdateCustomClassRequest, +): + client = AdaptationClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = { + "custom_class": { + "name": "projects/sample1/locations/sample2/customClasses/sample3" + } + } + request_init["custom_class"] = { + "name": "projects/sample1/locations/sample2/customClasses/sample3", + "custom_class_id": "custom_class_id_value", + "items": [{"value": "value_value"}], + } + 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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.update_custom_class(request) + + +def test_update_custom_class_rest_flattened(): + client = AdaptationClient( + 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 = resource.CustomClass() + + # get arguments that satisfy an http rule for this method + sample_request = { + "custom_class": { + "name": "projects/sample1/locations/sample2/customClasses/sample3" + } + } + + # get truthy value for each flattened field + mock_args = dict( + custom_class=resource.CustomClass(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 + pb_return_value = resource.CustomClass.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.update_custom_class(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1p1beta1/{custom_class.name=projects/*/locations/*/customClasses/*}" + % client.transport._host, + args[1], + ) + + +def test_update_custom_class_rest_flattened_error(transport: str = "rest"): + client = AdaptationClient( + credentials=ga_credentials.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_custom_class( + cloud_speech_adaptation.UpdateCustomClassRequest(), + custom_class=resource.CustomClass(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +def test_update_custom_class_rest_error(): + client = AdaptationClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + cloud_speech_adaptation.DeleteCustomClassRequest, + dict, + ], +) +def test_delete_custom_class_rest(request_type): + client = AdaptationClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/customClasses/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 = None + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = "" + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.delete_custom_class(request) + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_custom_class_rest_required_fields( + request_type=cloud_speech_adaptation.DeleteCustomClassRequest, +): + transport_class = transports.AdaptationRestTransport + + 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, + including_default_value_fields=False, + use_integers_for_enums=False, + ) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).delete_custom_class._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).delete_custom_class._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 = AdaptationClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = None + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "delete", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = "" + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.delete_custom_class(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_delete_custom_class_rest_unset_required_fields(): + transport = transports.AdaptationRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.delete_custom_class._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_custom_class_rest_interceptors(null_interceptor): + transport = transports.AdaptationRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.AdaptationRestInterceptor(), + ) + client = AdaptationClient(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.AdaptationRestInterceptor, "pre_delete_custom_class" + ) as pre: + pre.assert_not_called() + pb_message = cloud_speech_adaptation.DeleteCustomClassRequest.pb( + cloud_speech_adaptation.DeleteCustomClassRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + + request = cloud_speech_adaptation.DeleteCustomClassRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + + client.delete_custom_class( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + + +def test_delete_custom_class_rest_bad_request( + transport: str = "rest", + request_type=cloud_speech_adaptation.DeleteCustomClassRequest, +): + client = AdaptationClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/customClasses/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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.delete_custom_class(request) + + +def test_delete_custom_class_rest_flattened(): + client = AdaptationClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = None + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/customClasses/sample3" + } + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = "" + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.delete_custom_class(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1p1beta1/{name=projects/*/locations/*/customClasses/*}" + % client.transport._host, + args[1], + ) + + +def test_delete_custom_class_rest_flattened_error(transport: str = "rest"): + client = AdaptationClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.delete_custom_class( + cloud_speech_adaptation.DeleteCustomClassRequest(), + name="name_value", + ) + + +def test_delete_custom_class_rest_error(): + client = AdaptationClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.AdaptationGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = AdaptationClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.AdaptationGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = AdaptationClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.AdaptationGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = AdaptationClient( + client_options=options, + transport=transport, + ) + + # It is an error to provide an api_key and a credential. + options = mock.Mock() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = AdaptationClient( + client_options=options, credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.AdaptationGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = AdaptationClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.AdaptationGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = AdaptationClient(transport=transport) + assert client.transport is transport + + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.AdaptationGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.AdaptationGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.AdaptationGrpcTransport, + transports.AdaptationGrpcAsyncIOTransport, + transports.AdaptationRestTransport, + ], +) +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() + + +@pytest.mark.parametrize( + "transport_name", + [ + "grpc", + "rest", + ], +) +def test_transport_kind(transport_name): + transport = AdaptationClient.get_transport_class(transport_name)( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert transport.kind == transport_name + + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = AdaptationClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.AdaptationGrpcTransport, + ) + + +def test_adaptation_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.AdaptationTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json", + ) + + +def test_adaptation_base_transport(): + # Instantiate the base transport. + with mock.patch( + "google.cloud.speech_v1p1beta1.services.adaptation.transports.AdaptationTransport.__init__" + ) as Transport: + Transport.return_value = None + transport = transports.AdaptationTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + "create_phrase_set", + "get_phrase_set", + "list_phrase_set", + "update_phrase_set", + "delete_phrase_set", + "create_custom_class", + "get_custom_class", + "list_custom_classes", + "update_custom_class", + "delete_custom_class", + "get_operation", + "list_operations", + ) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + with pytest.raises(NotImplementedError): + transport.close() + + # Catch all for all remaining methods and properties + remainder = [ + "kind", + ] + for r in remainder: + with pytest.raises(NotImplementedError): + getattr(transport, r)() + + +def test_adaptation_base_transport_with_credentials_file(): + # Instantiate the base transport with a credentials file + with mock.patch.object( + google.auth, "load_credentials_from_file", autospec=True + ) as load_creds, mock.patch( + "google.cloud.speech_v1p1beta1.services.adaptation.transports.AdaptationTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.AdaptationTransport( + credentials_file="credentials.json", + quota_project_id="octopus", + ) + load_creds.assert_called_once_with( + "credentials.json", + scopes=None, + default_scopes=("https://www.googleapis.com/auth/cloud-platform",), + quota_project_id="octopus", + ) + + +def test_adaptation_base_transport_with_adc(): + # Test the default credentials are used if credentials and credentials_file are None. + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch( + "google.cloud.speech_v1p1beta1.services.adaptation.transports.AdaptationTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.AdaptationTransport() + adc.assert_called_once() + + +def test_adaptation_auth_adc(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + AdaptationClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=("https://www.googleapis.com/auth/cloud-platform",), + quota_project_id=None, + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.AdaptationGrpcTransport, + transports.AdaptationGrpcAsyncIOTransport, + ], +) +def test_adaptation_transport_auth_adc(transport_class): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + adc.assert_called_once_with( + scopes=["1", "2"], + default_scopes=("https://www.googleapis.com/auth/cloud-platform",), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.AdaptationGrpcTransport, + transports.AdaptationGrpcAsyncIOTransport, + transports.AdaptationRestTransport, + ], +) +def test_adaptation_transport_auth_gdch_credentials(transport_class): + host = "https://language.com" + api_audience_tests = [None, "https://language2.com"] + api_audience_expect = [host, "https://language2.com"] + for t, e in zip(api_audience_tests, api_audience_expect): + with mock.patch.object(google.auth, "default", autospec=True) as adc: + gdch_mock = mock.MagicMock() + type(gdch_mock).with_gdch_audience = mock.PropertyMock( + return_value=gdch_mock + ) + adc.return_value = (gdch_mock, None) + transport_class(host=host, api_audience=t) + gdch_mock.with_gdch_audience.assert_called_once_with(e) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.AdaptationGrpcTransport, grpc_helpers), + (transports.AdaptationGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +def test_adaptation_transport_create_channel(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + + create_channel.assert_called_with( + "speech.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + default_scopes=("https://www.googleapis.com/auth/cloud-platform",), + scopes=["1", "2"], + default_host="speech.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class", + [transports.AdaptationGrpcTransport, transports.AdaptationGrpcAsyncIOTransport], +) +def test_adaptation_grpc_transport_client_cert_source_for_mtls(transport_class): + cred = ga_credentials.AnonymousCredentials() + + # Check ssl_channel_credentials is used if provided. + with mock.patch.object(transport_class, "create_channel") as mock_create_channel: + mock_ssl_channel_creds = mock.Mock() + transport_class( + host="squid.clam.whelk", + credentials=cred, + ssl_channel_credentials=mock_ssl_channel_creds, + ) + mock_create_channel.assert_called_once_with( + "squid.clam.whelk:443", + credentials=cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_channel_creds, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls + # is used. + with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): + with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: + transport_class( + credentials=cred, + client_cert_source_for_mtls=client_cert_source_callback, + ) + expected_cert, expected_key = client_cert_source_callback() + mock_ssl_cred.assert_called_once_with( + certificate_chain=expected_cert, private_key=expected_key + ) + + +def test_adaptation_http_transport_client_cert_source_for_mtls(): + cred = ga_credentials.AnonymousCredentials() + with mock.patch( + "google.auth.transport.requests.AuthorizedSession.configure_mtls_channel" + ) as mock_configure_mtls_channel: + transports.AdaptationRestTransport( + credentials=cred, client_cert_source_for_mtls=client_cert_source_callback + ) + mock_configure_mtls_channel.assert_called_once_with(client_cert_source_callback) + + +@pytest.mark.parametrize( + "transport_name", + [ + "grpc", + "grpc_asyncio", + "rest", + ], +) +def test_adaptation_host_no_port(transport_name): + client = AdaptationClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions( + api_endpoint="speech.googleapis.com" + ), + transport=transport_name, + ) + assert client.transport._host == ( + "speech.googleapis.com:443" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://speech.googleapis.com" + ) + + +@pytest.mark.parametrize( + "transport_name", + [ + "grpc", + "grpc_asyncio", + "rest", + ], +) +def test_adaptation_host_with_port(transport_name): + client = AdaptationClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions( + api_endpoint="speech.googleapis.com:8000" + ), + transport=transport_name, + ) + assert client.transport._host == ( + "speech.googleapis.com:8000" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://speech.googleapis.com:8000" + ) + + +@pytest.mark.parametrize( + "transport_name", + [ + "rest", + ], +) +def test_adaptation_client_transport_session_collision(transport_name): + creds1 = ga_credentials.AnonymousCredentials() + creds2 = ga_credentials.AnonymousCredentials() + client1 = AdaptationClient( + credentials=creds1, + transport=transport_name, + ) + client2 = AdaptationClient( + credentials=creds2, + transport=transport_name, + ) + session1 = client1.transport.create_phrase_set._session + session2 = client2.transport.create_phrase_set._session + assert session1 != session2 + session1 = client1.transport.get_phrase_set._session + session2 = client2.transport.get_phrase_set._session + assert session1 != session2 + session1 = client1.transport.list_phrase_set._session + session2 = client2.transport.list_phrase_set._session + assert session1 != session2 + session1 = client1.transport.update_phrase_set._session + session2 = client2.transport.update_phrase_set._session + assert session1 != session2 + session1 = client1.transport.delete_phrase_set._session + session2 = client2.transport.delete_phrase_set._session + assert session1 != session2 + session1 = client1.transport.create_custom_class._session + session2 = client2.transport.create_custom_class._session + assert session1 != session2 + session1 = client1.transport.get_custom_class._session + session2 = client2.transport.get_custom_class._session + assert session1 != session2 + session1 = client1.transport.list_custom_classes._session + session2 = client2.transport.list_custom_classes._session + assert session1 != session2 + session1 = client1.transport.update_custom_class._session + session2 = client2.transport.update_custom_class._session + assert session1 != session2 + session1 = client1.transport.delete_custom_class._session + session2 = client2.transport.delete_custom_class._session + assert session1 != session2 + + +def test_adaptation_grpc_transport_channel(): + channel = grpc.secure_channel("http://localhost/", grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.AdaptationGrpcTransport( + host="squid.clam.whelk", + channel=channel, + ) + assert transport.grpc_channel == channel + assert transport._host == "squid.clam.whelk:443" + assert transport._ssl_channel_credentials == None + + +def test_adaptation_grpc_asyncio_transport_channel(): + channel = aio.secure_channel("http://localhost/", grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.AdaptationGrpcAsyncIOTransport( + host="squid.clam.whelk", + channel=channel, + ) + assert transport.grpc_channel == channel + assert transport._host == "squid.clam.whelk:443" + assert transport._ssl_channel_credentials == None + + +# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are +# removed from grpc/grpc_asyncio transport constructor. +@pytest.mark.parametrize( + "transport_class", + [transports.AdaptationGrpcTransport, transports.AdaptationGrpcAsyncIOTransport], +) +def test_adaptation_transport_channel_mtls_with_client_cert_source(transport_class): + with mock.patch( + "grpc.ssl_channel_credentials", autospec=True + ) as grpc_ssl_channel_cred: + with mock.patch.object( + transport_class, "create_channel" + ) as grpc_create_channel: + mock_ssl_cred = mock.Mock() + grpc_ssl_channel_cred.return_value = mock_ssl_cred + + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + + cred = ga_credentials.AnonymousCredentials() + with pytest.warns(DeprecationWarning): + with mock.patch.object(google.auth, "default") as adc: + adc.return_value = (cred, None) + transport = transport_class( + host="squid.clam.whelk", + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=client_cert_source_callback, + ) + adc.assert_called_once() + + grpc_ssl_channel_cred.assert_called_once_with( + certificate_chain=b"cert bytes", private_key=b"key bytes" + ) + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel + assert transport._ssl_channel_credentials == mock_ssl_cred + + +# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are +# removed from grpc/grpc_asyncio transport constructor. +@pytest.mark.parametrize( + "transport_class", + [transports.AdaptationGrpcTransport, transports.AdaptationGrpcAsyncIOTransport], +) +def test_adaptation_transport_channel_mtls_with_adc(transport_class): + mock_ssl_cred = mock.Mock() + with mock.patch.multiple( + "google.auth.transport.grpc.SslCredentials", + __init__=mock.Mock(return_value=None), + ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred), + ): + with mock.patch.object( + transport_class, "create_channel" + ) as grpc_create_channel: + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + mock_cred = mock.Mock() + + with pytest.warns(DeprecationWarning): + transport = transport_class( + host="squid.clam.whelk", + credentials=mock_cred, + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=None, + ) + + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=mock_cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel + + +def test_custom_class_path(): + project = "squid" + location = "clam" + custom_class = "whelk" + expected = ( + "projects/{project}/locations/{location}/customClasses/{custom_class}".format( + project=project, + location=location, + custom_class=custom_class, + ) + ) + actual = AdaptationClient.custom_class_path(project, location, custom_class) + assert expected == actual + + +def test_parse_custom_class_path(): + expected = { + "project": "octopus", + "location": "oyster", + "custom_class": "nudibranch", + } + path = AdaptationClient.custom_class_path(**expected) + + # Check that the path construction is reversible. + actual = AdaptationClient.parse_custom_class_path(path) + assert expected == actual + + +def test_phrase_set_path(): + project = "cuttlefish" + location = "mussel" + phrase_set = "winkle" + expected = "projects/{project}/locations/{location}/phraseSets/{phrase_set}".format( + project=project, + location=location, + phrase_set=phrase_set, + ) + actual = AdaptationClient.phrase_set_path(project, location, phrase_set) + assert expected == actual + + +def test_parse_phrase_set_path(): + expected = { + "project": "nautilus", + "location": "scallop", + "phrase_set": "abalone", + } + path = AdaptationClient.phrase_set_path(**expected) + + # Check that the path construction is reversible. + actual = AdaptationClient.parse_phrase_set_path(path) + assert expected == actual + + +def test_common_billing_account_path(): + billing_account = "squid" + expected = "billingAccounts/{billing_account}".format( + billing_account=billing_account, + ) + actual = AdaptationClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "clam", + } + path = AdaptationClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = AdaptationClient.parse_common_billing_account_path(path) + assert expected == actual + + +def test_common_folder_path(): + folder = "whelk" + expected = "folders/{folder}".format( + folder=folder, + ) + actual = AdaptationClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "octopus", + } + path = AdaptationClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = AdaptationClient.parse_common_folder_path(path) + assert expected == actual + + +def test_common_organization_path(): + organization = "oyster" + expected = "organizations/{organization}".format( + organization=organization, + ) + actual = AdaptationClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "nudibranch", + } + path = AdaptationClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = AdaptationClient.parse_common_organization_path(path) + assert expected == actual + + +def test_common_project_path(): + project = "cuttlefish" + expected = "projects/{project}".format( + project=project, + ) + actual = AdaptationClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "mussel", + } + path = AdaptationClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = AdaptationClient.parse_common_project_path(path) + assert expected == actual + + +def test_common_location_path(): + project = "winkle" + location = "nautilus" + expected = "projects/{project}/locations/{location}".format( + project=project, + location=location, + ) + actual = AdaptationClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "scallop", + "location": "abalone", + } + path = AdaptationClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = AdaptationClient.parse_common_location_path(path) + assert expected == actual + + +def test_client_with_default_client_info(): + client_info = gapic_v1.client_info.ClientInfo() + + with mock.patch.object( + transports.AdaptationTransport, "_prep_wrapped_messages" + ) as prep: + client = AdaptationClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object( + transports.AdaptationTransport, "_prep_wrapped_messages" + ) as prep: + transport_class = AdaptationClient.get_transport_class() + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + +@pytest.mark.asyncio +async def test_transport_close_async(): + client = AdaptationAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc_asyncio", + ) + with mock.patch.object( + type(getattr(client.transport, "grpc_channel")), "close" + ) as close: + async with client: + close.assert_not_called() + close.assert_called_once() + + +def test_get_operation_rest_bad_request( + transport: str = "rest", request_type=operations_pb2.GetOperationRequest +): + client = AdaptationClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + request = request_type() + request = json_format.ParseDict({"name": "sample1"}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_operation(request) -# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are -# removed from grpc/grpc_asyncio transport constructor. @pytest.mark.parametrize( - "transport_class", - [transports.AdaptationGrpcTransport, transports.AdaptationGrpcAsyncIOTransport], + "request_type", + [ + operations_pb2.GetOperationRequest, + dict, + ], ) -def test_adaptation_transport_channel_mtls_with_adc(transport_class): - mock_ssl_cred = mock.Mock() - with mock.patch.multiple( - "google.auth.transport.grpc.SslCredentials", - __init__=mock.Mock(return_value=None), - ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred), +def test_get_operation_rest(request_type): + client = AdaptationClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request_init = {"name": "sample1"} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation() + + # 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 + + response = client.get_operation(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.Operation) + + +def test_list_operations_rest_bad_request( + transport: str = "rest", request_type=operations_pb2.ListOperationsRequest +): + client = AdaptationClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + request = request_type() + request = json_format.ParseDict({}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest ): - with mock.patch.object( - transport_class, "create_channel" - ) as grpc_create_channel: - mock_grpc_channel = mock.Mock() - grpc_create_channel.return_value = mock_grpc_channel - mock_cred = mock.Mock() + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_operations(request) - with pytest.warns(DeprecationWarning): - transport = transport_class( - host="squid.clam.whelk", - credentials=mock_cred, - api_mtls_endpoint="mtls.squid.clam.whelk", - client_cert_source=None, - ) - grpc_create_channel.assert_called_once_with( - "mtls.squid.clam.whelk:443", - credentials=mock_cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_cred, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - assert transport.grpc_channel == mock_grpc_channel +@pytest.mark.parametrize( + "request_type", + [ + operations_pb2.ListOperationsRequest, + dict, + ], +) +def test_list_operations_rest(request_type): + client = AdaptationClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request_init = {} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.ListOperationsResponse() + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) -def test_custom_class_path(): - project = "squid" - location = "clam" - custom_class = "whelk" - expected = ( - "projects/{project}/locations/{location}/customClasses/{custom_class}".format( - project=project, - location=location, - custom_class=custom_class, + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.list_operations(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.ListOperationsResponse) + + +def test_get_operation(transport: str = "grpc"): + client = AdaptationClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.GetOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation() + response = client.get_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.Operation) + + +@pytest.mark.asyncio +async def test_get_operation_async(transport: str = "grpc"): + client = AdaptationAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.GetOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation() ) + response = await client.get_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.Operation) + + +def test_get_operation_field_headers(): + client = AdaptationClient( + credentials=ga_credentials.AnonymousCredentials(), ) - actual = AdaptationClient.custom_class_path(project, location, custom_class) - assert expected == actual + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = operations_pb2.GetOperationRequest() + request.name = "locations" -def test_parse_custom_class_path(): - expected = { - "project": "octopus", - "location": "oyster", - "custom_class": "nudibranch", - } - path = AdaptationClient.custom_class_path(**expected) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + call.return_value = operations_pb2.Operation() - # Check that the path construction is reversible. - actual = AdaptationClient.parse_custom_class_path(path) - assert expected == actual + client.get_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=locations", + ) in kw["metadata"] -def test_phrase_set_path(): - project = "cuttlefish" - location = "mussel" - phrase_set = "winkle" - expected = "projects/{project}/locations/{location}/phraseSets/{phrase_set}".format( - project=project, - location=location, - phrase_set=phrase_set, + +@pytest.mark.asyncio +async def test_get_operation_field_headers_async(): + client = AdaptationAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), ) - actual = AdaptationClient.phrase_set_path(project, location, phrase_set) - assert expected == actual + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = operations_pb2.GetOperationRequest() + request.name = "locations" -def test_parse_phrase_set_path(): - expected = { - "project": "nautilus", - "location": "scallop", - "phrase_set": "abalone", - } - path = AdaptationClient.phrase_set_path(**expected) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation() + ) + await client.get_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request - # Check that the path construction is reversible. - actual = AdaptationClient.parse_phrase_set_path(path) - assert expected == actual + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=locations", + ) in kw["metadata"] -def test_common_billing_account_path(): - billing_account = "squid" - expected = "billingAccounts/{billing_account}".format( - billing_account=billing_account, +def test_get_operation_from_dict(): + client = AdaptationClient( + credentials=ga_credentials.AnonymousCredentials(), ) - actual = AdaptationClient.common_billing_account_path(billing_account) - assert expected == actual + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation() + response = client.get_operation( + request={ + "name": "locations", + } + ) + call.assert_called() -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "clam", - } - path = AdaptationClient.common_billing_account_path(**expected) - # Check that the path construction is reversible. - actual = AdaptationClient.parse_common_billing_account_path(path) - assert expected == actual +@pytest.mark.asyncio +async def test_get_operation_from_dict_async(): + client = AdaptationAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation() + ) + response = await client.get_operation( + request={ + "name": "locations", + } + ) + call.assert_called() -def test_common_folder_path(): - folder = "whelk" - expected = "folders/{folder}".format( - folder=folder, +def test_list_operations(transport: str = "grpc"): + client = AdaptationClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, ) - actual = AdaptationClient.common_folder_path(folder) - assert expected == actual + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.ListOperationsRequest() -def test_parse_common_folder_path(): - expected = { - "folder": "octopus", - } - path = AdaptationClient.common_folder_path(**expected) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.ListOperationsResponse() + response = client.list_operations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request - # Check that the path construction is reversible. - actual = AdaptationClient.parse_common_folder_path(path) - assert expected == actual + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.ListOperationsResponse) -def test_common_organization_path(): - organization = "oyster" - expected = "organizations/{organization}".format( - organization=organization, +@pytest.mark.asyncio +async def test_list_operations_async(transport: str = "grpc"): + client = AdaptationAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, ) - actual = AdaptationClient.common_organization_path(organization) - assert expected == actual + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.ListOperationsRequest() -def test_parse_common_organization_path(): - expected = { - "organization": "nudibranch", - } - path = AdaptationClient.common_organization_path(**expected) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.ListOperationsResponse() + ) + response = await client.list_operations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request - # Check that the path construction is reversible. - actual = AdaptationClient.parse_common_organization_path(path) - assert expected == actual + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.ListOperationsResponse) -def test_common_project_path(): - project = "cuttlefish" - expected = "projects/{project}".format( - project=project, +def test_list_operations_field_headers(): + client = AdaptationClient( + credentials=ga_credentials.AnonymousCredentials(), ) - actual = AdaptationClient.common_project_path(project) - assert expected == actual + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = operations_pb2.ListOperationsRequest() + request.name = "locations" -def test_parse_common_project_path(): - expected = { - "project": "mussel", - } - path = AdaptationClient.common_project_path(**expected) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + call.return_value = operations_pb2.ListOperationsResponse() - # Check that the path construction is reversible. - actual = AdaptationClient.parse_common_project_path(path) - assert expected == actual + client.list_operations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=locations", + ) in kw["metadata"] -def test_common_location_path(): - project = "winkle" - location = "nautilus" - expected = "projects/{project}/locations/{location}".format( - project=project, - location=location, - ) - actual = AdaptationClient.common_location_path(project, location) - assert expected == actual +@pytest.mark.asyncio +async def test_list_operations_field_headers_async(): + client = AdaptationAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) -def test_parse_common_location_path(): - expected = { - "project": "scallop", - "location": "abalone", - } - path = AdaptationClient.common_location_path(**expected) + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = operations_pb2.ListOperationsRequest() + request.name = "locations" - # Check that the path construction is reversible. - actual = AdaptationClient.parse_common_location_path(path) - assert expected == actual + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.ListOperationsResponse() + ) + await client.list_operations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=locations", + ) in kw["metadata"] -def test_client_with_default_client_info(): - client_info = gapic_v1.client_info.ClientInfo() - with mock.patch.object( - transports.AdaptationTransport, "_prep_wrapped_messages" - ) as prep: - client = AdaptationClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) +def test_list_operations_from_dict(): + client = AdaptationClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.ListOperationsResponse() - with mock.patch.object( - transports.AdaptationTransport, "_prep_wrapped_messages" - ) as prep: - transport_class = AdaptationClient.get_transport_class() - transport = transport_class( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, + response = client.list_operations( + request={ + "name": "locations", + } ) - prep.assert_called_once_with(client_info) + call.assert_called() @pytest.mark.asyncio -async def test_transport_close_async(): +async def test_list_operations_from_dict_async(): client = AdaptationAsyncClient( credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", ) - with mock.patch.object( - type(getattr(client.transport, "grpc_channel")), "close" - ) as close: - async with client: - close.assert_not_called() - close.assert_called_once() + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.ListOperationsResponse() + ) + response = await client.list_operations( + request={ + "name": "locations", + } + ) + call.assert_called() def test_transport_close(): transports = { + "rest": "_session", "grpc": "_grpc_channel", } @@ -4213,6 +7611,7 @@ def test_transport_close(): def test_client_ctx(): transports = [ + "rest", "grpc", ] for transport in transports: diff --git a/tests/unit/gapic/speech_v1p1beta1/test_speech.py b/tests/unit/gapic/speech_v1p1beta1/test_speech.py index f52e2781..fd01fe14 100644 --- a/tests/unit/gapic/speech_v1p1beta1/test_speech.py +++ b/tests/unit/gapic/speech_v1p1beta1/test_speech.py @@ -24,10 +24,17 @@ import grpc from grpc.experimental import aio +from collections.abc import Iterable +from google.protobuf import json_format +import json import math import pytest from proto.marshal.rules.dates import DurationRule, TimestampRule from proto.marshal.rules import wrappers +from requests import Response +from requests import Request, PreparedRequest +from requests.sessions import Session +from google.protobuf import json_format from google.api_core import client_options from google.api_core import exceptions as core_exceptions @@ -97,6 +104,7 @@ def test__get_default_mtls_endpoint(): [ (SpeechClient, "grpc"), (SpeechAsyncClient, "grpc_asyncio"), + (SpeechClient, "rest"), ], ) def test_speech_client_from_service_account_info(client_class, transport_name): @@ -110,7 +118,11 @@ def test_speech_client_from_service_account_info(client_class, transport_name): assert client.transport._credentials == creds assert isinstance(client, client_class) - assert client.transport._host == ("speech.googleapis.com:443") + assert client.transport._host == ( + "speech.googleapis.com:443" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://speech.googleapis.com" + ) @pytest.mark.parametrize( @@ -118,6 +130,7 @@ def test_speech_client_from_service_account_info(client_class, transport_name): [ (transports.SpeechGrpcTransport, "grpc"), (transports.SpeechGrpcAsyncIOTransport, "grpc_asyncio"), + (transports.SpeechRestTransport, "rest"), ], ) def test_speech_client_service_account_always_use_jwt(transport_class, transport_name): @@ -141,6 +154,7 @@ def test_speech_client_service_account_always_use_jwt(transport_class, transport [ (SpeechClient, "grpc"), (SpeechAsyncClient, "grpc_asyncio"), + (SpeechClient, "rest"), ], ) def test_speech_client_from_service_account_file(client_class, transport_name): @@ -161,13 +175,18 @@ def test_speech_client_from_service_account_file(client_class, transport_name): assert client.transport._credentials == creds assert isinstance(client, client_class) - assert client.transport._host == ("speech.googleapis.com:443") + assert client.transport._host == ( + "speech.googleapis.com:443" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://speech.googleapis.com" + ) def test_speech_client_get_transport_class(): transport = SpeechClient.get_transport_class() available_transports = [ transports.SpeechGrpcTransport, + transports.SpeechRestTransport, ] assert transport in available_transports @@ -180,6 +199,7 @@ def test_speech_client_get_transport_class(): [ (SpeechClient, transports.SpeechGrpcTransport, "grpc"), (SpeechAsyncClient, transports.SpeechGrpcAsyncIOTransport, "grpc_asyncio"), + (SpeechClient, transports.SpeechRestTransport, "rest"), ], ) @mock.patch.object( @@ -319,6 +339,8 @@ def test_speech_client_client_options(client_class, transport_class, transport_n "grpc_asyncio", "false", ), + (SpeechClient, transports.SpeechRestTransport, "rest", "true"), + (SpeechClient, transports.SpeechRestTransport, "rest", "false"), ], ) @mock.patch.object( @@ -504,6 +526,7 @@ def test_speech_client_get_mtls_endpoint_and_cert_source(client_class): [ (SpeechClient, transports.SpeechGrpcTransport, "grpc"), (SpeechAsyncClient, transports.SpeechGrpcAsyncIOTransport, "grpc_asyncio"), + (SpeechClient, transports.SpeechRestTransport, "rest"), ], ) def test_speech_client_client_options_scopes( @@ -539,6 +562,7 @@ def test_speech_client_client_options_scopes( "grpc_asyncio", grpc_helpers_async, ), + (SpeechClient, transports.SpeechRestTransport, "rest", None), ], ) def test_speech_client_client_options_credentials_file( @@ -1111,6 +1135,569 @@ async def test_streaming_recognize_async_from_dict(): await test_streaming_recognize_async(request_type=dict) +@pytest.mark.parametrize( + "request_type", + [ + cloud_speech.RecognizeRequest, + dict, + ], +) +def test_recognize_rest(request_type): + client = SpeechClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = cloud_speech.RecognizeResponse( + request_id=1077, + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = cloud_speech.RecognizeResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.recognize(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, cloud_speech.RecognizeResponse) + assert response.request_id == 1077 + + +def test_recognize_rest_required_fields(request_type=cloud_speech.RecognizeRequest): + transport_class = transports.SpeechRestTransport + + request_init = {} + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False, + ) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).recognize._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).recognize._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + + client = SpeechClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = cloud_speech.RecognizeResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force 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 + + pb_return_value = cloud_speech.RecognizeResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.recognize(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_recognize_rest_unset_required_fields(): + transport = transports.SpeechRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.recognize._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(()) + & set( + ( + "config", + "audio", + ) + ) + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_recognize_rest_interceptors(null_interceptor): + transport = transports.SpeechRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SpeechRestInterceptor(), + ) + client = SpeechClient(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.SpeechRestInterceptor, "post_recognize" + ) as post, mock.patch.object( + transports.SpeechRestInterceptor, "pre_recognize" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = cloud_speech.RecognizeRequest.pb(cloud_speech.RecognizeRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = cloud_speech.RecognizeResponse.to_json( + cloud_speech.RecognizeResponse() + ) + + request = cloud_speech.RecognizeRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = cloud_speech.RecognizeResponse() + + client.recognize( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_recognize_rest_bad_request( + transport: str = "rest", request_type=cloud_speech.RecognizeRequest +): + client = SpeechClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.recognize(request) + + +def test_recognize_rest_flattened(): + client = SpeechClient( + 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 = cloud_speech.RecognizeResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {} + + # get truthy value for each flattened field + mock_args = dict( + config=cloud_speech.RecognitionConfig( + encoding=cloud_speech.RecognitionConfig.AudioEncoding.LINEAR16 + ), + audio=cloud_speech.RecognitionAudio(content=b"content_blob"), + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = cloud_speech.RecognizeResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.recognize(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1p1beta1/speech:recognize" % client.transport._host, args[1] + ) + + +def test_recognize_rest_flattened_error(transport: str = "rest"): + client = SpeechClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.recognize( + cloud_speech.RecognizeRequest(), + config=cloud_speech.RecognitionConfig( + encoding=cloud_speech.RecognitionConfig.AudioEncoding.LINEAR16 + ), + audio=cloud_speech.RecognitionAudio(content=b"content_blob"), + ) + + +def test_recognize_rest_error(): + client = SpeechClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + cloud_speech.LongRunningRecognizeRequest, + dict, + ], +) +def test_long_running_recognize_rest(request_type): + client = SpeechClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # 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 + response = client.long_running_recognize(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_long_running_recognize_rest_required_fields( + request_type=cloud_speech.LongRunningRecognizeRequest, +): + transport_class = transports.SpeechRestTransport + + request_init = {} + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False, + ) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).long_running_recognize._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).long_running_recognize._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + + client = SpeechClient( + 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 + + response = client.long_running_recognize(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_long_running_recognize_rest_unset_required_fields(): + transport = transports.SpeechRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.long_running_recognize._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(()) + & set( + ( + "config", + "audio", + ) + ) + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_long_running_recognize_rest_interceptors(null_interceptor): + transport = transports.SpeechRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SpeechRestInterceptor(), + ) + client = SpeechClient(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.SpeechRestInterceptor, "post_long_running_recognize" + ) as post, mock.patch.object( + transports.SpeechRestInterceptor, "pre_long_running_recognize" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = cloud_speech.LongRunningRecognizeRequest.pb( + cloud_speech.LongRunningRecognizeRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson( + operations_pb2.Operation() + ) + + request = cloud_speech.LongRunningRecognizeRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.long_running_recognize( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_long_running_recognize_rest_bad_request( + transport: str = "rest", request_type=cloud_speech.LongRunningRecognizeRequest +): + client = SpeechClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.long_running_recognize(request) + + +def test_long_running_recognize_rest_flattened(): + client = SpeechClient( + 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 = {} + + # get truthy value for each flattened field + mock_args = dict( + config=cloud_speech.RecognitionConfig( + encoding=cloud_speech.RecognitionConfig.AudioEncoding.LINEAR16 + ), + audio=cloud_speech.RecognitionAudio(content=b"content_blob"), + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.long_running_recognize(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1p1beta1/speech:longrunningrecognize" % client.transport._host, args[1] + ) + + +def test_long_running_recognize_rest_flattened_error(transport: str = "rest"): + client = SpeechClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.long_running_recognize( + cloud_speech.LongRunningRecognizeRequest(), + config=cloud_speech.RecognitionConfig( + encoding=cloud_speech.RecognitionConfig.AudioEncoding.LINEAR16 + ), + audio=cloud_speech.RecognitionAudio(content=b"content_blob"), + ) + + +def test_long_running_recognize_rest_error(): + client = SpeechClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +def test_streaming_recognize_rest_no_http_options(): + client = SpeechClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = cloud_speech.StreamingRecognizeRequest() + requests = [request] + with pytest.raises(RuntimeError): + client.streaming_recognize(requests) + + +def test_streaming_recognize_rest_error(): + client = SpeechClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # Since a `google.api.http` annotation is required for using a rest transport + # method, this should error. + with pytest.raises(NotImplementedError) as not_implemented_error: + client.streaming_recognize({}) + assert "Method StreamingRecognize is not available over REST transport" in str( + not_implemented_error.value + ) + + def test_credentials_transport_error(): # It is an error to provide credentials and a transport instance. transport = transports.SpeechGrpcTransport( @@ -1192,6 +1779,7 @@ def test_transport_get_channel(): [ transports.SpeechGrpcTransport, transports.SpeechGrpcAsyncIOTransport, + transports.SpeechRestTransport, ], ) def test_transport_adc(transport_class): @@ -1206,6 +1794,7 @@ def test_transport_adc(transport_class): "transport_name", [ "grpc", + "rest", ], ) def test_transport_kind(transport_name): @@ -1251,6 +1840,8 @@ def test_speech_base_transport(): "recognize", "long_running_recognize", "streaming_recognize", + "get_operation", + "list_operations", ) for method in methods: with pytest.raises(NotImplementedError): @@ -1342,6 +1933,7 @@ def test_speech_transport_auth_adc(transport_class): [ transports.SpeechGrpcTransport, transports.SpeechGrpcAsyncIOTransport, + transports.SpeechRestTransport, ], ) def test_speech_transport_auth_gdch_credentials(transport_class): @@ -1436,11 +2028,40 @@ def test_speech_grpc_transport_client_cert_source_for_mtls(transport_class): ) +def test_speech_http_transport_client_cert_source_for_mtls(): + cred = ga_credentials.AnonymousCredentials() + with mock.patch( + "google.auth.transport.requests.AuthorizedSession.configure_mtls_channel" + ) as mock_configure_mtls_channel: + transports.SpeechRestTransport( + credentials=cred, client_cert_source_for_mtls=client_cert_source_callback + ) + mock_configure_mtls_channel.assert_called_once_with(client_cert_source_callback) + + +def test_speech_rest_lro_client(): + client = SpeechClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + transport = client.transport + + # Ensure that we have a api-core operations client. + assert isinstance( + transport.operations_client, + operations_v1.AbstractOperationsClient, + ) + + # Ensure that subsequent calls to the property send the exact same object. + assert transport.operations_client is transport.operations_client + + @pytest.mark.parametrize( "transport_name", [ "grpc", "grpc_asyncio", + "rest", ], ) def test_speech_host_no_port(transport_name): @@ -1451,7 +2072,11 @@ def test_speech_host_no_port(transport_name): ), transport=transport_name, ) - assert client.transport._host == ("speech.googleapis.com:443") + assert client.transport._host == ( + "speech.googleapis.com:443" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://speech.googleapis.com" + ) @pytest.mark.parametrize( @@ -1459,6 +2084,7 @@ def test_speech_host_no_port(transport_name): [ "grpc", "grpc_asyncio", + "rest", ], ) def test_speech_host_with_port(transport_name): @@ -1469,7 +2095,39 @@ def test_speech_host_with_port(transport_name): ), transport=transport_name, ) - assert client.transport._host == ("speech.googleapis.com:8000") + assert client.transport._host == ( + "speech.googleapis.com:8000" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://speech.googleapis.com:8000" + ) + + +@pytest.mark.parametrize( + "transport_name", + [ + "rest", + ], +) +def test_speech_client_transport_session_collision(transport_name): + creds1 = ga_credentials.AnonymousCredentials() + creds2 = ga_credentials.AnonymousCredentials() + client1 = SpeechClient( + credentials=creds1, + transport=transport_name, + ) + client2 = SpeechClient( + credentials=creds2, + transport=transport_name, + ) + session1 = client1.transport.recognize._session + session2 = client2.transport.recognize._session + assert session1 != session2 + session1 = client1.transport.long_running_recognize._session + session2 = client2.transport.long_running_recognize._session + assert session1 != session2 + session1 = client1.transport.streaming_recognize._session + session2 = client2.transport.streaming_recognize._session + assert session1 != session2 def test_speech_grpc_transport_channel(): @@ -1818,8 +2476,411 @@ async def test_transport_close_async(): close.assert_called_once() +def test_get_operation_rest_bad_request( + transport: str = "rest", request_type=operations_pb2.GetOperationRequest +): + client = SpeechClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + request = request_type() + request = json_format.ParseDict({"name": "sample1"}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_operation(request) + + +@pytest.mark.parametrize( + "request_type", + [ + operations_pb2.GetOperationRequest, + dict, + ], +) +def test_get_operation_rest(request_type): + client = SpeechClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request_init = {"name": "sample1"} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation() + + # 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 + + response = client.get_operation(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.Operation) + + +def test_list_operations_rest_bad_request( + transport: str = "rest", request_type=operations_pb2.ListOperationsRequest +): + client = SpeechClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + request = request_type() + request = json_format.ParseDict({}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_operations(request) + + +@pytest.mark.parametrize( + "request_type", + [ + operations_pb2.ListOperationsRequest, + dict, + ], +) +def test_list_operations_rest(request_type): + client = SpeechClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request_init = {} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.ListOperationsResponse() + + # 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 + + response = client.list_operations(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.ListOperationsResponse) + + +def test_get_operation(transport: str = "grpc"): + client = SpeechClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.GetOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation() + response = client.get_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.Operation) + + +@pytest.mark.asyncio +async def test_get_operation_async(transport: str = "grpc"): + client = SpeechAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.GetOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation() + ) + response = await client.get_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.Operation) + + +def test_get_operation_field_headers(): + client = SpeechClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = operations_pb2.GetOperationRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + call.return_value = operations_pb2.Operation() + + client.get_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=locations", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_get_operation_field_headers_async(): + client = SpeechAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = operations_pb2.GetOperationRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation() + ) + await client.get_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=locations", + ) in kw["metadata"] + + +def test_get_operation_from_dict(): + client = SpeechClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation() + + response = client.get_operation( + request={ + "name": "locations", + } + ) + call.assert_called() + + +@pytest.mark.asyncio +async def test_get_operation_from_dict_async(): + client = SpeechAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation() + ) + response = await client.get_operation( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_list_operations(transport: str = "grpc"): + client = SpeechClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.ListOperationsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.ListOperationsResponse() + response = client.list_operations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.ListOperationsResponse) + + +@pytest.mark.asyncio +async def test_list_operations_async(transport: str = "grpc"): + client = SpeechAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.ListOperationsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.ListOperationsResponse() + ) + response = await client.list_operations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.ListOperationsResponse) + + +def test_list_operations_field_headers(): + client = SpeechClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = operations_pb2.ListOperationsRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + call.return_value = operations_pb2.ListOperationsResponse() + + client.list_operations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=locations", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_list_operations_field_headers_async(): + client = SpeechAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = operations_pb2.ListOperationsRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.ListOperationsResponse() + ) + await client.list_operations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=locations", + ) in kw["metadata"] + + +def test_list_operations_from_dict(): + client = SpeechClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.ListOperationsResponse() + + response = client.list_operations( + request={ + "name": "locations", + } + ) + call.assert_called() + + +@pytest.mark.asyncio +async def test_list_operations_from_dict_async(): + client = SpeechAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.ListOperationsResponse() + ) + response = await client.list_operations( + request={ + "name": "locations", + } + ) + call.assert_called() + + def test_transport_close(): transports = { + "rest": "_session", "grpc": "_grpc_channel", } @@ -1837,6 +2898,7 @@ def test_transport_close(): def test_client_ctx(): transports = [ + "rest", "grpc", ] for transport in transports: diff --git a/tests/unit/gapic/speech_v2/test_speech.py b/tests/unit/gapic/speech_v2/test_speech.py index 941427b0..857deb3c 100644 --- a/tests/unit/gapic/speech_v2/test_speech.py +++ b/tests/unit/gapic/speech_v2/test_speech.py @@ -24,10 +24,17 @@ import grpc from grpc.experimental import aio +from collections.abc import Iterable +from google.protobuf import json_format +import json import math import pytest from proto.marshal.rules.dates import DurationRule, TimestampRule from proto.marshal.rules import wrappers +from requests import Response +from requests import Request, PreparedRequest +from requests.sessions import Session +from google.protobuf import json_format from google.api_core import client_options from google.api_core import exceptions as core_exceptions @@ -97,6 +104,7 @@ def test__get_default_mtls_endpoint(): [ (SpeechClient, "grpc"), (SpeechAsyncClient, "grpc_asyncio"), + (SpeechClient, "rest"), ], ) def test_speech_client_from_service_account_info(client_class, transport_name): @@ -110,7 +118,11 @@ def test_speech_client_from_service_account_info(client_class, transport_name): assert client.transport._credentials == creds assert isinstance(client, client_class) - assert client.transport._host == ("speech.googleapis.com:443") + assert client.transport._host == ( + "speech.googleapis.com:443" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://speech.googleapis.com" + ) @pytest.mark.parametrize( @@ -118,6 +130,7 @@ def test_speech_client_from_service_account_info(client_class, transport_name): [ (transports.SpeechGrpcTransport, "grpc"), (transports.SpeechGrpcAsyncIOTransport, "grpc_asyncio"), + (transports.SpeechRestTransport, "rest"), ], ) def test_speech_client_service_account_always_use_jwt(transport_class, transport_name): @@ -141,6 +154,7 @@ def test_speech_client_service_account_always_use_jwt(transport_class, transport [ (SpeechClient, "grpc"), (SpeechAsyncClient, "grpc_asyncio"), + (SpeechClient, "rest"), ], ) def test_speech_client_from_service_account_file(client_class, transport_name): @@ -161,13 +175,18 @@ def test_speech_client_from_service_account_file(client_class, transport_name): assert client.transport._credentials == creds assert isinstance(client, client_class) - assert client.transport._host == ("speech.googleapis.com:443") + assert client.transport._host == ( + "speech.googleapis.com:443" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://speech.googleapis.com" + ) def test_speech_client_get_transport_class(): transport = SpeechClient.get_transport_class() available_transports = [ transports.SpeechGrpcTransport, + transports.SpeechRestTransport, ] assert transport in available_transports @@ -180,6 +199,7 @@ def test_speech_client_get_transport_class(): [ (SpeechClient, transports.SpeechGrpcTransport, "grpc"), (SpeechAsyncClient, transports.SpeechGrpcAsyncIOTransport, "grpc_asyncio"), + (SpeechClient, transports.SpeechRestTransport, "rest"), ], ) @mock.patch.object( @@ -319,6 +339,8 @@ def test_speech_client_client_options(client_class, transport_class, transport_n "grpc_asyncio", "false", ), + (SpeechClient, transports.SpeechRestTransport, "rest", "true"), + (SpeechClient, transports.SpeechRestTransport, "rest", "false"), ], ) @mock.patch.object( @@ -504,6 +526,7 @@ def test_speech_client_get_mtls_endpoint_and_cert_source(client_class): [ (SpeechClient, transports.SpeechGrpcTransport, "grpc"), (SpeechAsyncClient, transports.SpeechGrpcAsyncIOTransport, "grpc_asyncio"), + (SpeechClient, transports.SpeechRestTransport, "rest"), ], ) def test_speech_client_client_options_scopes( @@ -539,6 +562,7 @@ def test_speech_client_client_options_scopes( "grpc_asyncio", grpc_helpers_async, ), + (SpeechClient, transports.SpeechRestTransport, "rest", None), ], ) def test_speech_client_client_options_credentials_file( @@ -6751,194 +6775,6969 @@ async def test_undelete_phrase_set_flattened_error_async(): ) -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.SpeechGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), +@pytest.mark.parametrize( + "request_type", + [ + cloud_speech.CreateRecognizerRequest, + dict, + ], +) +def test_create_recognizer_rest(request_type): + client = SpeechClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2"} + request_init["recognizer"] = { + "name": "name_value", + "uid": "uid_value", + "display_name": "display_name_value", + "model": "model_value", + "language_codes": ["language_codes_value1", "language_codes_value2"], + "default_recognition_config": { + "auto_decoding_config": {}, + "explicit_decoding_config": { + "encoding": 1, + "sample_rate_hertz": 1817, + "audio_channel_count": 2002, + }, + "features": { + "profanity_filter": True, + "enable_word_time_offsets": True, + "enable_word_confidence": True, + "enable_automatic_punctuation": True, + "enable_spoken_punctuation": True, + "enable_spoken_emojis": True, + "multi_channel_mode": 1, + "diarization_config": { + "min_speaker_count": 1814, + "max_speaker_count": 1816, + }, + "max_alternatives": 1719, + }, + "adaptation": { + "phrase_sets": [ + { + "phrase_set": "phrase_set_value", + "inline_phrase_set": { + "name": "name_value", + "uid": "uid_value", + "phrases": [{"value": "value_value", "boost": 0.551}], + "boost": 0.551, + "display_name": "display_name_value", + "state": 2, + "create_time": {"seconds": 751, "nanos": 543}, + "update_time": {}, + "delete_time": {}, + "expire_time": {}, + "annotations": {}, + "etag": "etag_value", + "reconciling": True, + "kms_key_name": "kms_key_name_value", + "kms_key_version_name": "kms_key_version_name_value", + }, + } + ], + "custom_classes": [ + { + "name": "name_value", + "uid": "uid_value", + "display_name": "display_name_value", + "items": [{"value": "value_value"}], + "state": 2, + "create_time": {}, + "update_time": {}, + "delete_time": {}, + "expire_time": {}, + "annotations": {}, + "etag": "etag_value", + "reconciling": True, + "kms_key_name": "kms_key_name_value", + "kms_key_version_name": "kms_key_version_name_value", + } + ], + }, + }, + "annotations": {}, + "state": 2, + "create_time": {}, + "update_time": {}, + "delete_time": {}, + "expire_time": {}, + "etag": "etag_value", + "reconciling": True, + "kms_key_name": "kms_key_name_value", + "kms_key_version_name": "kms_key_version_name_value", + } + 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 = 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 + response = client.create_recognizer(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_create_recognizer_rest_required_fields( + request_type=cloud_speech.CreateRecognizerRequest, +): + transport_class = transports.SpeechRestTransport + + 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, + including_default_value_fields=False, + use_integers_for_enums=False, + ) ) - with pytest.raises(ValueError): - client = SpeechClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).create_recognizer._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = "parent_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).create_recognizer._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "recognizer_id", + "validate_only", ) + ) + jsonified_request.update(unset_fields) - # It is an error to provide a credentials file and a transport instance. - transport = transports.SpeechGrpcTransport( + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + + client = SpeechClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - with pytest.raises(ValueError): - client = SpeechClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) + request = request_type(**request_init) - # It is an error to provide an api_key and a transport instance. - transport = transports.SpeechGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), + # 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 + + response = client.create_recognizer(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_create_recognizer_rest_unset_required_fields(): + transport = transports.SpeechRestTransport( + credentials=ga_credentials.AnonymousCredentials ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = SpeechClient( - client_options=options, - transport=transport, - ) - # It is an error to provide an api_key and a credential. - options = mock.Mock() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = SpeechClient( - client_options=options, credentials=ga_credentials.AnonymousCredentials() + unset_fields = transport.create_recognizer._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "recognizerId", + "validateOnly", + ) + ) + & set( + ( + "recognizer", + "parent", + ) ) + ) - # It is an error to provide scopes and a transport instance. - transport = transports.SpeechGrpcTransport( + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_recognizer_rest_interceptors(null_interceptor): + transport = transports.SpeechRestTransport( credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SpeechRestInterceptor(), ) - with pytest.raises(ValueError): - client = SpeechClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, + client = SpeechClient(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.SpeechRestInterceptor, "post_create_recognizer" + ) as post, mock.patch.object( + transports.SpeechRestInterceptor, "pre_create_recognizer" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = cloud_speech.CreateRecognizerRequest.pb( + cloud_speech.CreateRecognizerRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson( + operations_pb2.Operation() ) + request = cloud_speech.CreateRecognizerRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.SpeechGrpcTransport( + client.create_recognizer( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_create_recognizer_rest_bad_request( + transport: str = "rest", request_type=cloud_speech.CreateRecognizerRequest +): + client = SpeechClient( credentials=ga_credentials.AnonymousCredentials(), + transport=transport, ) - client = SpeechClient(transport=transport) - assert client.transport is transport + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2"} + request_init["recognizer"] = { + "name": "name_value", + "uid": "uid_value", + "display_name": "display_name_value", + "model": "model_value", + "language_codes": ["language_codes_value1", "language_codes_value2"], + "default_recognition_config": { + "auto_decoding_config": {}, + "explicit_decoding_config": { + "encoding": 1, + "sample_rate_hertz": 1817, + "audio_channel_count": 2002, + }, + "features": { + "profanity_filter": True, + "enable_word_time_offsets": True, + "enable_word_confidence": True, + "enable_automatic_punctuation": True, + "enable_spoken_punctuation": True, + "enable_spoken_emojis": True, + "multi_channel_mode": 1, + "diarization_config": { + "min_speaker_count": 1814, + "max_speaker_count": 1816, + }, + "max_alternatives": 1719, + }, + "adaptation": { + "phrase_sets": [ + { + "phrase_set": "phrase_set_value", + "inline_phrase_set": { + "name": "name_value", + "uid": "uid_value", + "phrases": [{"value": "value_value", "boost": 0.551}], + "boost": 0.551, + "display_name": "display_name_value", + "state": 2, + "create_time": {"seconds": 751, "nanos": 543}, + "update_time": {}, + "delete_time": {}, + "expire_time": {}, + "annotations": {}, + "etag": "etag_value", + "reconciling": True, + "kms_key_name": "kms_key_name_value", + "kms_key_version_name": "kms_key_version_name_value", + }, + } + ], + "custom_classes": [ + { + "name": "name_value", + "uid": "uid_value", + "display_name": "display_name_value", + "items": [{"value": "value_value"}], + "state": 2, + "create_time": {}, + "update_time": {}, + "delete_time": {}, + "expire_time": {}, + "annotations": {}, + "etag": "etag_value", + "reconciling": True, + "kms_key_name": "kms_key_name_value", + "kms_key_version_name": "kms_key_version_name_value", + } + ], + }, + }, + "annotations": {}, + "state": 2, + "create_time": {}, + "update_time": {}, + "delete_time": {}, + "expire_time": {}, + "etag": "etag_value", + "reconciling": True, + "kms_key_name": "kms_key_name_value", + "kms_key_version_name": "kms_key_version_name_value", + } + request = request_type(**request_init) -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.SpeechGrpcTransport( + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.create_recognizer(request) + + +def test_create_recognizer_rest_flattened(): + client = SpeechClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - channel = transport.grpc_channel - assert channel - transport = transports.SpeechGrpcAsyncIOTransport( + # Mock the http request call within the method and 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", + recognizer=cloud_speech.Recognizer(name="name_value"), + recognizer_id="recognizer_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 + + client.create_recognizer(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v2/{parent=projects/*/locations/*}/recognizers" + % client.transport._host, + args[1], + ) + + +def test_create_recognizer_rest_flattened_error(transport: str = "rest"): + client = SpeechClient( credentials=ga_credentials.AnonymousCredentials(), + transport=transport, ) - channel = transport.grpc_channel - assert channel + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.create_recognizer( + cloud_speech.CreateRecognizerRequest(), + parent="parent_value", + recognizer=cloud_speech.Recognizer(name="name_value"), + recognizer_id="recognizer_id_value", + ) -@pytest.mark.parametrize( - "transport_class", - [ - transports.SpeechGrpcTransport, - transports.SpeechGrpcAsyncIOTransport, - ], -) -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_create_recognizer_rest_error(): + client = SpeechClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) @pytest.mark.parametrize( - "transport_name", + "request_type", [ - "grpc", + cloud_speech.ListRecognizersRequest, + dict, ], ) -def test_transport_kind(transport_name): - transport = SpeechClient.get_transport_class(transport_name)( +def test_list_recognizers_rest(request_type): + client = SpeechClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - assert transport.kind == transport_name + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2"} + request = request_type(**request_init) -def test_transport_grpc_default(): - # A client should use the gRPC transport by default. - client = SpeechClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert isinstance( - client.transport, - transports.SpeechGrpcTransport, - ) + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = cloud_speech.ListRecognizersResponse( + next_page_token="next_page_token_value", + ) + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = cloud_speech.ListRecognizersResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) -def test_speech_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.SpeechTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json", + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.list_recognizers(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListRecognizersPager) + assert response.next_page_token == "next_page_token_value" + + +def test_list_recognizers_rest_required_fields( + request_type=cloud_speech.ListRecognizersRequest, +): + transport_class = transports.SpeechRestTransport + + 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, + including_default_value_fields=False, + use_integers_for_enums=False, ) + ) + # verify fields with default values are dropped -def test_speech_base_transport(): - # Instantiate the base transport. - with mock.patch( - "google.cloud.speech_v2.services.speech.transports.SpeechTransport.__init__" - ) as Transport: - Transport.return_value = None - transport = transports.SpeechTransport( - credentials=ga_credentials.AnonymousCredentials(), + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).list_recognizers._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = "parent_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).list_recognizers._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "page_size", + "page_token", + "show_deleted", ) + ) + jsonified_request.update(unset_fields) - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - "create_recognizer", - "list_recognizers", - "get_recognizer", - "update_recognizer", - "delete_recognizer", - "undelete_recognizer", - "recognize", - "streaming_recognize", - "batch_recognize", - "get_config", - "update_config", - "create_custom_class", - "list_custom_classes", - "get_custom_class", - "update_custom_class", - "delete_custom_class", - "undelete_custom_class", - "create_phrase_set", - "list_phrase_sets", - "get_phrase_set", - "update_phrase_set", - "delete_phrase_set", - "undelete_phrase_set", - "get_operation", - "cancel_operation", - "delete_operation", - "list_operations", + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + + client = SpeechClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - for method in methods: - with pytest.raises(NotImplementedError): - getattr(transport, method)(request=object()) + request = request_type(**request_init) - with pytest.raises(NotImplementedError): - transport.close() + # Designate an appropriate value for the returned response. + return_value = cloud_speech.ListRecognizersResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force 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 - # Additionally, the LRO client (a property) should - # also raise NotImplementedError - with pytest.raises(NotImplementedError): - transport.operations_client + response_value = Response() + response_value.status_code = 200 - # Catch all for all remaining methods and properties - remainder = [ - "kind", - ] - for r in remainder: - with pytest.raises(NotImplementedError): - getattr(transport, r)() + pb_return_value = cloud_speech.ListRecognizersResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value -def test_speech_base_transport_with_credentials_file(): - # Instantiate the base transport with a credentials file + response = client.list_recognizers(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_list_recognizers_rest_unset_required_fields(): + transport = transports.SpeechRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.list_recognizers._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "pageSize", + "pageToken", + "showDeleted", + ) + ) + & set(("parent",)) + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_recognizers_rest_interceptors(null_interceptor): + transport = transports.SpeechRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SpeechRestInterceptor(), + ) + client = SpeechClient(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.SpeechRestInterceptor, "post_list_recognizers" + ) as post, mock.patch.object( + transports.SpeechRestInterceptor, "pre_list_recognizers" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = cloud_speech.ListRecognizersRequest.pb( + cloud_speech.ListRecognizersRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = cloud_speech.ListRecognizersResponse.to_json( + cloud_speech.ListRecognizersResponse() + ) + + request = cloud_speech.ListRecognizersRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = cloud_speech.ListRecognizersResponse() + + client.list_recognizers( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_recognizers_rest_bad_request( + transport: str = "rest", request_type=cloud_speech.ListRecognizersRequest +): + client = SpeechClient( + 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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_recognizers(request) + + +def test_list_recognizers_rest_flattened(): + client = SpeechClient( + 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 = cloud_speech.ListRecognizersResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {"parent": "projects/sample1/locations/sample2"} + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = cloud_speech.ListRecognizersResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.list_recognizers(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v2/{parent=projects/*/locations/*}/recognizers" + % client.transport._host, + args[1], + ) + + +def test_list_recognizers_rest_flattened_error(transport: str = "rest"): + client = SpeechClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_recognizers( + cloud_speech.ListRecognizersRequest(), + parent="parent_value", + ) + + +def test_list_recognizers_rest_pager(transport: str = "rest"): + client = SpeechClient( + 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 = ( + cloud_speech.ListRecognizersResponse( + recognizers=[ + cloud_speech.Recognizer(), + cloud_speech.Recognizer(), + cloud_speech.Recognizer(), + ], + next_page_token="abc", + ), + cloud_speech.ListRecognizersResponse( + recognizers=[], + next_page_token="def", + ), + cloud_speech.ListRecognizersResponse( + recognizers=[ + cloud_speech.Recognizer(), + ], + next_page_token="ghi", + ), + cloud_speech.ListRecognizersResponse( + recognizers=[ + cloud_speech.Recognizer(), + cloud_speech.Recognizer(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple( + cloud_speech.ListRecognizersResponse.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_recognizers(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, cloud_speech.Recognizer) for i in results) + + pages = list(client.list_recognizers(request=sample_request).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.parametrize( + "request_type", + [ + cloud_speech.GetRecognizerRequest, + dict, + ], +) +def test_get_recognizer_rest(request_type): + client = SpeechClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/recognizers/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 = cloud_speech.Recognizer( + name="name_value", + uid="uid_value", + display_name="display_name_value", + model="model_value", + language_codes=["language_codes_value"], + state=cloud_speech.Recognizer.State.ACTIVE, + etag="etag_value", + reconciling=True, + kms_key_name="kms_key_name_value", + kms_key_version_name="kms_key_version_name_value", + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = cloud_speech.Recognizer.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.get_recognizer(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, cloud_speech.Recognizer) + assert response.name == "name_value" + assert response.uid == "uid_value" + assert response.display_name == "display_name_value" + assert response.model == "model_value" + assert response.language_codes == ["language_codes_value"] + assert response.state == cloud_speech.Recognizer.State.ACTIVE + assert response.etag == "etag_value" + assert response.reconciling is True + assert response.kms_key_name == "kms_key_name_value" + assert response.kms_key_version_name == "kms_key_version_name_value" + + +def test_get_recognizer_rest_required_fields( + request_type=cloud_speech.GetRecognizerRequest, +): + transport_class = transports.SpeechRestTransport + + 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, + including_default_value_fields=False, + use_integers_for_enums=False, + ) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get_recognizer._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_recognizer._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 = SpeechClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = cloud_speech.Recognizer() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force 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 + + pb_return_value = cloud_speech.Recognizer.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.get_recognizer(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_get_recognizer_rest_unset_required_fields(): + transport = transports.SpeechRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.get_recognizer._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_recognizer_rest_interceptors(null_interceptor): + transport = transports.SpeechRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SpeechRestInterceptor(), + ) + client = SpeechClient(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.SpeechRestInterceptor, "post_get_recognizer" + ) as post, mock.patch.object( + transports.SpeechRestInterceptor, "pre_get_recognizer" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = cloud_speech.GetRecognizerRequest.pb( + cloud_speech.GetRecognizerRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = cloud_speech.Recognizer.to_json( + cloud_speech.Recognizer() + ) + + request = cloud_speech.GetRecognizerRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = cloud_speech.Recognizer() + + client.get_recognizer( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_recognizer_rest_bad_request( + transport: str = "rest", request_type=cloud_speech.GetRecognizerRequest +): + client = SpeechClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/recognizers/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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_recognizer(request) + + +def test_get_recognizer_rest_flattened(): + client = SpeechClient( + 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 = cloud_speech.Recognizer() + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/recognizers/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 + pb_return_value = cloud_speech.Recognizer.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.get_recognizer(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v2/{name=projects/*/locations/*/recognizers/*}" + % client.transport._host, + args[1], + ) + + +def test_get_recognizer_rest_flattened_error(transport: str = "rest"): + client = SpeechClient( + credentials=ga_credentials.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_recognizer( + cloud_speech.GetRecognizerRequest(), + name="name_value", + ) + + +def test_get_recognizer_rest_error(): + client = SpeechClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + cloud_speech.UpdateRecognizerRequest, + dict, + ], +) +def test_update_recognizer_rest(request_type): + client = SpeechClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = { + "recognizer": {"name": "projects/sample1/locations/sample2/recognizers/sample3"} + } + request_init["recognizer"] = { + "name": "projects/sample1/locations/sample2/recognizers/sample3", + "uid": "uid_value", + "display_name": "display_name_value", + "model": "model_value", + "language_codes": ["language_codes_value1", "language_codes_value2"], + "default_recognition_config": { + "auto_decoding_config": {}, + "explicit_decoding_config": { + "encoding": 1, + "sample_rate_hertz": 1817, + "audio_channel_count": 2002, + }, + "features": { + "profanity_filter": True, + "enable_word_time_offsets": True, + "enable_word_confidence": True, + "enable_automatic_punctuation": True, + "enable_spoken_punctuation": True, + "enable_spoken_emojis": True, + "multi_channel_mode": 1, + "diarization_config": { + "min_speaker_count": 1814, + "max_speaker_count": 1816, + }, + "max_alternatives": 1719, + }, + "adaptation": { + "phrase_sets": [ + { + "phrase_set": "phrase_set_value", + "inline_phrase_set": { + "name": "name_value", + "uid": "uid_value", + "phrases": [{"value": "value_value", "boost": 0.551}], + "boost": 0.551, + "display_name": "display_name_value", + "state": 2, + "create_time": {"seconds": 751, "nanos": 543}, + "update_time": {}, + "delete_time": {}, + "expire_time": {}, + "annotations": {}, + "etag": "etag_value", + "reconciling": True, + "kms_key_name": "kms_key_name_value", + "kms_key_version_name": "kms_key_version_name_value", + }, + } + ], + "custom_classes": [ + { + "name": "name_value", + "uid": "uid_value", + "display_name": "display_name_value", + "items": [{"value": "value_value"}], + "state": 2, + "create_time": {}, + "update_time": {}, + "delete_time": {}, + "expire_time": {}, + "annotations": {}, + "etag": "etag_value", + "reconciling": True, + "kms_key_name": "kms_key_name_value", + "kms_key_version_name": "kms_key_version_name_value", + } + ], + }, + }, + "annotations": {}, + "state": 2, + "create_time": {}, + "update_time": {}, + "delete_time": {}, + "expire_time": {}, + "etag": "etag_value", + "reconciling": True, + "kms_key_name": "kms_key_name_value", + "kms_key_version_name": "kms_key_version_name_value", + } + 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 = 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 + response = client.update_recognizer(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_update_recognizer_rest_required_fields( + request_type=cloud_speech.UpdateRecognizerRequest, +): + transport_class = transports.SpeechRestTransport + + request_init = {} + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False, + ) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).update_recognizer._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).update_recognizer._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "update_mask", + "validate_only", + ) + ) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + + client = SpeechClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "patch", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.update_recognizer(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_update_recognizer_rest_unset_required_fields(): + transport = transports.SpeechRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.update_recognizer._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "updateMask", + "validateOnly", + ) + ) + & set(("recognizer",)) + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_recognizer_rest_interceptors(null_interceptor): + transport = transports.SpeechRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SpeechRestInterceptor(), + ) + client = SpeechClient(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.SpeechRestInterceptor, "post_update_recognizer" + ) as post, mock.patch.object( + transports.SpeechRestInterceptor, "pre_update_recognizer" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = cloud_speech.UpdateRecognizerRequest.pb( + cloud_speech.UpdateRecognizerRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson( + operations_pb2.Operation() + ) + + request = cloud_speech.UpdateRecognizerRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.update_recognizer( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_recognizer_rest_bad_request( + transport: str = "rest", request_type=cloud_speech.UpdateRecognizerRequest +): + client = SpeechClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = { + "recognizer": {"name": "projects/sample1/locations/sample2/recognizers/sample3"} + } + request_init["recognizer"] = { + "name": "projects/sample1/locations/sample2/recognizers/sample3", + "uid": "uid_value", + "display_name": "display_name_value", + "model": "model_value", + "language_codes": ["language_codes_value1", "language_codes_value2"], + "default_recognition_config": { + "auto_decoding_config": {}, + "explicit_decoding_config": { + "encoding": 1, + "sample_rate_hertz": 1817, + "audio_channel_count": 2002, + }, + "features": { + "profanity_filter": True, + "enable_word_time_offsets": True, + "enable_word_confidence": True, + "enable_automatic_punctuation": True, + "enable_spoken_punctuation": True, + "enable_spoken_emojis": True, + "multi_channel_mode": 1, + "diarization_config": { + "min_speaker_count": 1814, + "max_speaker_count": 1816, + }, + "max_alternatives": 1719, + }, + "adaptation": { + "phrase_sets": [ + { + "phrase_set": "phrase_set_value", + "inline_phrase_set": { + "name": "name_value", + "uid": "uid_value", + "phrases": [{"value": "value_value", "boost": 0.551}], + "boost": 0.551, + "display_name": "display_name_value", + "state": 2, + "create_time": {"seconds": 751, "nanos": 543}, + "update_time": {}, + "delete_time": {}, + "expire_time": {}, + "annotations": {}, + "etag": "etag_value", + "reconciling": True, + "kms_key_name": "kms_key_name_value", + "kms_key_version_name": "kms_key_version_name_value", + }, + } + ], + "custom_classes": [ + { + "name": "name_value", + "uid": "uid_value", + "display_name": "display_name_value", + "items": [{"value": "value_value"}], + "state": 2, + "create_time": {}, + "update_time": {}, + "delete_time": {}, + "expire_time": {}, + "annotations": {}, + "etag": "etag_value", + "reconciling": True, + "kms_key_name": "kms_key_name_value", + "kms_key_version_name": "kms_key_version_name_value", + } + ], + }, + }, + "annotations": {}, + "state": 2, + "create_time": {}, + "update_time": {}, + "delete_time": {}, + "expire_time": {}, + "etag": "etag_value", + "reconciling": True, + "kms_key_name": "kms_key_name_value", + "kms_key_version_name": "kms_key_version_name_value", + } + 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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.update_recognizer(request) + + +def test_update_recognizer_rest_flattened(): + client = SpeechClient( + 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 = { + "recognizer": { + "name": "projects/sample1/locations/sample2/recognizers/sample3" + } + } + + # get truthy value for each flattened field + mock_args = dict( + recognizer=cloud_speech.Recognizer(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 + + client.update_recognizer(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v2/{recognizer.name=projects/*/locations/*/recognizers/*}" + % client.transport._host, + args[1], + ) + + +def test_update_recognizer_rest_flattened_error(transport: str = "rest"): + client = SpeechClient( + credentials=ga_credentials.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_recognizer( + cloud_speech.UpdateRecognizerRequest(), + recognizer=cloud_speech.Recognizer(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +def test_update_recognizer_rest_error(): + client = SpeechClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + cloud_speech.DeleteRecognizerRequest, + dict, + ], +) +def test_delete_recognizer_rest(request_type): + client = SpeechClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/recognizers/sample3"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = 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 + response = client.delete_recognizer(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_delete_recognizer_rest_required_fields( + request_type=cloud_speech.DeleteRecognizerRequest, +): + transport_class = transports.SpeechRestTransport + + 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, + including_default_value_fields=False, + use_integers_for_enums=False, + ) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).delete_recognizer._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_recognizer._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "allow_missing", + "etag", + "validate_only", + ) + ) + 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 = SpeechClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "delete", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.delete_recognizer(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_delete_recognizer_rest_unset_required_fields(): + transport = transports.SpeechRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.delete_recognizer._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "allowMissing", + "etag", + "validateOnly", + ) + ) + & set(("name",)) + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_recognizer_rest_interceptors(null_interceptor): + transport = transports.SpeechRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SpeechRestInterceptor(), + ) + client = SpeechClient(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.SpeechRestInterceptor, "post_delete_recognizer" + ) as post, mock.patch.object( + transports.SpeechRestInterceptor, "pre_delete_recognizer" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = cloud_speech.DeleteRecognizerRequest.pb( + cloud_speech.DeleteRecognizerRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson( + operations_pb2.Operation() + ) + + request = cloud_speech.DeleteRecognizerRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.delete_recognizer( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_delete_recognizer_rest_bad_request( + transport: str = "rest", request_type=cloud_speech.DeleteRecognizerRequest +): + client = SpeechClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/recognizers/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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.delete_recognizer(request) + + +def test_delete_recognizer_rest_flattened(): + client = SpeechClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/recognizers/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 + + client.delete_recognizer(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v2/{name=projects/*/locations/*/recognizers/*}" + % client.transport._host, + args[1], + ) + + +def test_delete_recognizer_rest_flattened_error(transport: str = "rest"): + client = SpeechClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.delete_recognizer( + cloud_speech.DeleteRecognizerRequest(), + name="name_value", + ) + + +def test_delete_recognizer_rest_error(): + client = SpeechClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + cloud_speech.UndeleteRecognizerRequest, + dict, + ], +) +def test_undelete_recognizer_rest(request_type): + client = SpeechClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/recognizers/sample3"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = 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 + response = client.undelete_recognizer(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_undelete_recognizer_rest_required_fields( + request_type=cloud_speech.UndeleteRecognizerRequest, +): + transport_class = transports.SpeechRestTransport + + 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, + including_default_value_fields=False, + use_integers_for_enums=False, + ) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).undelete_recognizer._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() + ).undelete_recognizer._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 = SpeechClient( + 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 + + response = client.undelete_recognizer(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_undelete_recognizer_rest_unset_required_fields(): + transport = transports.SpeechRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.undelete_recognizer._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_undelete_recognizer_rest_interceptors(null_interceptor): + transport = transports.SpeechRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SpeechRestInterceptor(), + ) + client = SpeechClient(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.SpeechRestInterceptor, "post_undelete_recognizer" + ) as post, mock.patch.object( + transports.SpeechRestInterceptor, "pre_undelete_recognizer" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = cloud_speech.UndeleteRecognizerRequest.pb( + cloud_speech.UndeleteRecognizerRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson( + operations_pb2.Operation() + ) + + request = cloud_speech.UndeleteRecognizerRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.undelete_recognizer( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_undelete_recognizer_rest_bad_request( + transport: str = "rest", request_type=cloud_speech.UndeleteRecognizerRequest +): + client = SpeechClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/recognizers/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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.undelete_recognizer(request) + + +def test_undelete_recognizer_rest_flattened(): + client = SpeechClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/recognizers/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 + + client.undelete_recognizer(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v2/{name=projects/*/locations/*/recognizers/*}:undelete" + % client.transport._host, + args[1], + ) + + +def test_undelete_recognizer_rest_flattened_error(transport: str = "rest"): + client = SpeechClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.undelete_recognizer( + cloud_speech.UndeleteRecognizerRequest(), + name="name_value", + ) + + +def test_undelete_recognizer_rest_error(): + client = SpeechClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + cloud_speech.RecognizeRequest, + dict, + ], +) +def test_recognize_rest(request_type): + client = SpeechClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = { + "recognizer": "projects/sample1/locations/sample2/recognizers/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 = cloud_speech.RecognizeResponse() + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = cloud_speech.RecognizeResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.recognize(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, cloud_speech.RecognizeResponse) + + +def test_recognize_rest_required_fields(request_type=cloud_speech.RecognizeRequest): + transport_class = transports.SpeechRestTransport + + request_init = {} + request_init["recognizer"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False, + ) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).recognize._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["recognizer"] = "recognizer_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).recognize._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "recognizer" in jsonified_request + assert jsonified_request["recognizer"] == "recognizer_value" + + client = SpeechClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = cloud_speech.RecognizeResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force 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 + + pb_return_value = cloud_speech.RecognizeResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.recognize(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_recognize_rest_unset_required_fields(): + transport = transports.SpeechRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.recognize._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("recognizer",))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_recognize_rest_interceptors(null_interceptor): + transport = transports.SpeechRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SpeechRestInterceptor(), + ) + client = SpeechClient(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.SpeechRestInterceptor, "post_recognize" + ) as post, mock.patch.object( + transports.SpeechRestInterceptor, "pre_recognize" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = cloud_speech.RecognizeRequest.pb(cloud_speech.RecognizeRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = cloud_speech.RecognizeResponse.to_json( + cloud_speech.RecognizeResponse() + ) + + request = cloud_speech.RecognizeRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = cloud_speech.RecognizeResponse() + + client.recognize( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_recognize_rest_bad_request( + transport: str = "rest", request_type=cloud_speech.RecognizeRequest +): + client = SpeechClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = { + "recognizer": "projects/sample1/locations/sample2/recognizers/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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.recognize(request) + + +def test_recognize_rest_flattened(): + client = SpeechClient( + 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 = cloud_speech.RecognizeResponse() + + # get arguments that satisfy an http rule for this method + sample_request = { + "recognizer": "projects/sample1/locations/sample2/recognizers/sample3" + } + + # get truthy value for each flattened field + mock_args = dict( + recognizer="recognizer_value", + config=cloud_speech.RecognitionConfig(auto_decoding_config=None), + config_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 + pb_return_value = cloud_speech.RecognizeResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.recognize(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v2/{recognizer=projects/*/locations/*/recognizers/*}:recognize" + % client.transport._host, + args[1], + ) + + +def test_recognize_rest_flattened_error(transport: str = "rest"): + client = SpeechClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.recognize( + cloud_speech.RecognizeRequest(), + recognizer="recognizer_value", + config=cloud_speech.RecognitionConfig(auto_decoding_config=None), + config_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + content=b"content_blob", + uri="uri_value", + ) + + +def test_recognize_rest_error(): + client = SpeechClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +def test_streaming_recognize_rest_no_http_options(): + client = SpeechClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = cloud_speech.StreamingRecognizeRequest() + requests = [request] + with pytest.raises(RuntimeError): + client.streaming_recognize(requests) + + +@pytest.mark.parametrize( + "request_type", + [ + cloud_speech.BatchRecognizeRequest, + dict, + ], +) +def test_batch_recognize_rest(request_type): + client = SpeechClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = { + "recognizer": "projects/sample1/locations/sample2/recognizers/sample3" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = 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 + response = client.batch_recognize(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_batch_recognize_rest_required_fields( + request_type=cloud_speech.BatchRecognizeRequest, +): + transport_class = transports.SpeechRestTransport + + request_init = {} + request_init["recognizer"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False, + ) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).batch_recognize._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["recognizer"] = "recognizer_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).batch_recognize._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "recognizer" in jsonified_request + assert jsonified_request["recognizer"] == "recognizer_value" + + client = SpeechClient( + 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 + + response = client.batch_recognize(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_batch_recognize_rest_unset_required_fields(): + transport = transports.SpeechRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.batch_recognize._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("recognizer",))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_batch_recognize_rest_interceptors(null_interceptor): + transport = transports.SpeechRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SpeechRestInterceptor(), + ) + client = SpeechClient(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.SpeechRestInterceptor, "post_batch_recognize" + ) as post, mock.patch.object( + transports.SpeechRestInterceptor, "pre_batch_recognize" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = cloud_speech.BatchRecognizeRequest.pb( + cloud_speech.BatchRecognizeRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson( + operations_pb2.Operation() + ) + + request = cloud_speech.BatchRecognizeRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.batch_recognize( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_batch_recognize_rest_bad_request( + transport: str = "rest", request_type=cloud_speech.BatchRecognizeRequest +): + client = SpeechClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = { + "recognizer": "projects/sample1/locations/sample2/recognizers/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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.batch_recognize(request) + + +def test_batch_recognize_rest_flattened(): + client = SpeechClient( + 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 = { + "recognizer": "projects/sample1/locations/sample2/recognizers/sample3" + } + + # get truthy value for each flattened field + mock_args = dict( + recognizer="recognizer_value", + config=cloud_speech.RecognitionConfig(auto_decoding_config=None), + config_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + files=[cloud_speech.BatchRecognizeFileMetadata(uri="uri_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 + + client.batch_recognize(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v2/{recognizer=projects/*/locations/*/recognizers/*}:batchRecognize" + % client.transport._host, + args[1], + ) + + +def test_batch_recognize_rest_flattened_error(transport: str = "rest"): + client = SpeechClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.batch_recognize( + cloud_speech.BatchRecognizeRequest(), + recognizer="recognizer_value", + config=cloud_speech.RecognitionConfig(auto_decoding_config=None), + config_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + files=[cloud_speech.BatchRecognizeFileMetadata(uri="uri_value")], + ) + + +def test_batch_recognize_rest_error(): + client = SpeechClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + cloud_speech.GetConfigRequest, + dict, + ], +) +def test_get_config_rest(request_type): + client = SpeechClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/config"} + 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 = cloud_speech.Config( + name="name_value", + kms_key_name="kms_key_name_value", + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = cloud_speech.Config.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.get_config(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, cloud_speech.Config) + assert response.name == "name_value" + assert response.kms_key_name == "kms_key_name_value" + + +def test_get_config_rest_required_fields(request_type=cloud_speech.GetConfigRequest): + transport_class = transports.SpeechRestTransport + + 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, + including_default_value_fields=False, + use_integers_for_enums=False, + ) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get_config._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_config._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 = SpeechClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = cloud_speech.Config() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force 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 + + pb_return_value = cloud_speech.Config.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.get_config(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_get_config_rest_unset_required_fields(): + transport = transports.SpeechRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.get_config._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_config_rest_interceptors(null_interceptor): + transport = transports.SpeechRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SpeechRestInterceptor(), + ) + client = SpeechClient(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.SpeechRestInterceptor, "post_get_config" + ) as post, mock.patch.object( + transports.SpeechRestInterceptor, "pre_get_config" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = cloud_speech.GetConfigRequest.pb(cloud_speech.GetConfigRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = cloud_speech.Config.to_json(cloud_speech.Config()) + + request = cloud_speech.GetConfigRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = cloud_speech.Config() + + client.get_config( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_config_rest_bad_request( + transport: str = "rest", request_type=cloud_speech.GetConfigRequest +): + client = SpeechClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/config"} + 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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_config(request) + + +def test_get_config_rest_flattened(): + client = SpeechClient( + 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 = cloud_speech.Config() + + # get arguments that satisfy an http rule for this method + sample_request = {"name": "projects/sample1/locations/sample2/config"} + + # 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 + pb_return_value = cloud_speech.Config.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.get_config(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v2/{name=projects/*/locations/*/config}" % client.transport._host, + args[1], + ) + + +def test_get_config_rest_flattened_error(transport: str = "rest"): + client = SpeechClient( + credentials=ga_credentials.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_config( + cloud_speech.GetConfigRequest(), + name="name_value", + ) + + +def test_get_config_rest_error(): + client = SpeechClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + cloud_speech.UpdateConfigRequest, + dict, + ], +) +def test_update_config_rest(request_type): + client = SpeechClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"config": {"name": "projects/sample1/locations/sample2/config"}} + request_init["config"] = { + "name": "projects/sample1/locations/sample2/config", + "kms_key_name": "kms_key_name_value", + "update_time": {"seconds": 751, "nanos": 543}, + } + 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 = cloud_speech.Config( + name="name_value", + kms_key_name="kms_key_name_value", + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = cloud_speech.Config.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.update_config(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, cloud_speech.Config) + assert response.name == "name_value" + assert response.kms_key_name == "kms_key_name_value" + + +def test_update_config_rest_required_fields( + request_type=cloud_speech.UpdateConfigRequest, +): + transport_class = transports.SpeechRestTransport + + request_init = {} + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False, + ) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).update_config._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).update_config._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("update_mask",)) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + + client = SpeechClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = cloud_speech.Config() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "patch", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + pb_return_value = cloud_speech.Config.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.update_config(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_update_config_rest_unset_required_fields(): + transport = transports.SpeechRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.update_config._get_unset_required_fields({}) + assert set(unset_fields) == (set(("updateMask",)) & set(("config",))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_config_rest_interceptors(null_interceptor): + transport = transports.SpeechRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SpeechRestInterceptor(), + ) + client = SpeechClient(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.SpeechRestInterceptor, "post_update_config" + ) as post, mock.patch.object( + transports.SpeechRestInterceptor, "pre_update_config" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = cloud_speech.UpdateConfigRequest.pb( + cloud_speech.UpdateConfigRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = cloud_speech.Config.to_json(cloud_speech.Config()) + + request = cloud_speech.UpdateConfigRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = cloud_speech.Config() + + client.update_config( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_config_rest_bad_request( + transport: str = "rest", request_type=cloud_speech.UpdateConfigRequest +): + client = SpeechClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"config": {"name": "projects/sample1/locations/sample2/config"}} + request_init["config"] = { + "name": "projects/sample1/locations/sample2/config", + "kms_key_name": "kms_key_name_value", + "update_time": {"seconds": 751, "nanos": 543}, + } + 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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.update_config(request) + + +def test_update_config_rest_flattened(): + client = SpeechClient( + 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 = cloud_speech.Config() + + # get arguments that satisfy an http rule for this method + sample_request = { + "config": {"name": "projects/sample1/locations/sample2/config"} + } + + # get truthy value for each flattened field + mock_args = dict( + config=cloud_speech.Config(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 + pb_return_value = cloud_speech.Config.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.update_config(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v2/{config.name=projects/*/locations/*/config}" + % client.transport._host, + args[1], + ) + + +def test_update_config_rest_flattened_error(transport: str = "rest"): + client = SpeechClient( + credentials=ga_credentials.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_config( + cloud_speech.UpdateConfigRequest(), + config=cloud_speech.Config(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +def test_update_config_rest_error(): + client = SpeechClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + cloud_speech.CreateCustomClassRequest, + dict, + ], +) +def test_create_custom_class_rest(request_type): + client = SpeechClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2"} + request_init["custom_class"] = { + "name": "name_value", + "uid": "uid_value", + "display_name": "display_name_value", + "items": [{"value": "value_value"}], + "state": 2, + "create_time": {"seconds": 751, "nanos": 543}, + "update_time": {}, + "delete_time": {}, + "expire_time": {}, + "annotations": {}, + "etag": "etag_value", + "reconciling": True, + "kms_key_name": "kms_key_name_value", + "kms_key_version_name": "kms_key_version_name_value", + } + 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 = 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 + response = client.create_custom_class(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_create_custom_class_rest_required_fields( + request_type=cloud_speech.CreateCustomClassRequest, +): + transport_class = transports.SpeechRestTransport + + 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, + including_default_value_fields=False, + use_integers_for_enums=False, + ) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).create_custom_class._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = "parent_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).create_custom_class._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "custom_class_id", + "validate_only", + ) + ) + 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 = SpeechClient( + 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 + + response = client.create_custom_class(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_create_custom_class_rest_unset_required_fields(): + transport = transports.SpeechRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.create_custom_class._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "customClassId", + "validateOnly", + ) + ) + & set( + ( + "customClass", + "parent", + ) + ) + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_custom_class_rest_interceptors(null_interceptor): + transport = transports.SpeechRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SpeechRestInterceptor(), + ) + client = SpeechClient(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.SpeechRestInterceptor, "post_create_custom_class" + ) as post, mock.patch.object( + transports.SpeechRestInterceptor, "pre_create_custom_class" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = cloud_speech.CreateCustomClassRequest.pb( + cloud_speech.CreateCustomClassRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson( + operations_pb2.Operation() + ) + + request = cloud_speech.CreateCustomClassRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.create_custom_class( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_create_custom_class_rest_bad_request( + transport: str = "rest", request_type=cloud_speech.CreateCustomClassRequest +): + client = SpeechClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2"} + request_init["custom_class"] = { + "name": "name_value", + "uid": "uid_value", + "display_name": "display_name_value", + "items": [{"value": "value_value"}], + "state": 2, + "create_time": {"seconds": 751, "nanos": 543}, + "update_time": {}, + "delete_time": {}, + "expire_time": {}, + "annotations": {}, + "etag": "etag_value", + "reconciling": True, + "kms_key_name": "kms_key_name_value", + "kms_key_version_name": "kms_key_version_name_value", + } + 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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.create_custom_class(request) + + +def test_create_custom_class_rest_flattened(): + client = SpeechClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # get arguments that satisfy an http rule for this method + sample_request = {"parent": "projects/sample1/locations/sample2"} + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + custom_class=cloud_speech.CustomClass(name="name_value"), + custom_class_id="custom_class_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 + + client.create_custom_class(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v2/{parent=projects/*/locations/*}/customClasses" + % client.transport._host, + args[1], + ) + + +def test_create_custom_class_rest_flattened_error(transport: str = "rest"): + client = SpeechClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.create_custom_class( + cloud_speech.CreateCustomClassRequest(), + parent="parent_value", + custom_class=cloud_speech.CustomClass(name="name_value"), + custom_class_id="custom_class_id_value", + ) + + +def test_create_custom_class_rest_error(): + client = SpeechClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + cloud_speech.ListCustomClassesRequest, + dict, + ], +) +def test_list_custom_classes_rest(request_type): + client = SpeechClient( + 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 = cloud_speech.ListCustomClassesResponse( + next_page_token="next_page_token_value", + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = cloud_speech.ListCustomClassesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.list_custom_classes(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListCustomClassesPager) + assert response.next_page_token == "next_page_token_value" + + +def test_list_custom_classes_rest_required_fields( + request_type=cloud_speech.ListCustomClassesRequest, +): + transport_class = transports.SpeechRestTransport + + 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, + including_default_value_fields=False, + use_integers_for_enums=False, + ) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).list_custom_classes._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = "parent_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).list_custom_classes._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "page_size", + "page_token", + "show_deleted", + ) + ) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + + client = SpeechClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = cloud_speech.ListCustomClassesResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force 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 + + pb_return_value = cloud_speech.ListCustomClassesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.list_custom_classes(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_list_custom_classes_rest_unset_required_fields(): + transport = transports.SpeechRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.list_custom_classes._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "pageSize", + "pageToken", + "showDeleted", + ) + ) + & set(("parent",)) + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_custom_classes_rest_interceptors(null_interceptor): + transport = transports.SpeechRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SpeechRestInterceptor(), + ) + client = SpeechClient(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.SpeechRestInterceptor, "post_list_custom_classes" + ) as post, mock.patch.object( + transports.SpeechRestInterceptor, "pre_list_custom_classes" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = cloud_speech.ListCustomClassesRequest.pb( + cloud_speech.ListCustomClassesRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = cloud_speech.ListCustomClassesResponse.to_json( + cloud_speech.ListCustomClassesResponse() + ) + + request = cloud_speech.ListCustomClassesRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = cloud_speech.ListCustomClassesResponse() + + client.list_custom_classes( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_custom_classes_rest_bad_request( + transport: str = "rest", request_type=cloud_speech.ListCustomClassesRequest +): + client = SpeechClient( + 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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_custom_classes(request) + + +def test_list_custom_classes_rest_flattened(): + client = SpeechClient( + 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 = cloud_speech.ListCustomClassesResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {"parent": "projects/sample1/locations/sample2"} + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = cloud_speech.ListCustomClassesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.list_custom_classes(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v2/{parent=projects/*/locations/*}/customClasses" + % client.transport._host, + args[1], + ) + + +def test_list_custom_classes_rest_flattened_error(transport: str = "rest"): + client = SpeechClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_custom_classes( + cloud_speech.ListCustomClassesRequest(), + parent="parent_value", + ) + + +def test_list_custom_classes_rest_pager(transport: str = "rest"): + client = SpeechClient( + 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 = ( + cloud_speech.ListCustomClassesResponse( + custom_classes=[ + cloud_speech.CustomClass(), + cloud_speech.CustomClass(), + cloud_speech.CustomClass(), + ], + next_page_token="abc", + ), + cloud_speech.ListCustomClassesResponse( + custom_classes=[], + next_page_token="def", + ), + cloud_speech.ListCustomClassesResponse( + custom_classes=[ + cloud_speech.CustomClass(), + ], + next_page_token="ghi", + ), + cloud_speech.ListCustomClassesResponse( + custom_classes=[ + cloud_speech.CustomClass(), + cloud_speech.CustomClass(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple( + cloud_speech.ListCustomClassesResponse.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_custom_classes(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, cloud_speech.CustomClass) for i in results) + + pages = list(client.list_custom_classes(request=sample_request).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.parametrize( + "request_type", + [ + cloud_speech.GetCustomClassRequest, + dict, + ], +) +def test_get_custom_class_rest(request_type): + client = SpeechClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/customClasses/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 = cloud_speech.CustomClass( + name="name_value", + uid="uid_value", + display_name="display_name_value", + state=cloud_speech.CustomClass.State.ACTIVE, + etag="etag_value", + reconciling=True, + kms_key_name="kms_key_name_value", + kms_key_version_name="kms_key_version_name_value", + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = cloud_speech.CustomClass.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.get_custom_class(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, cloud_speech.CustomClass) + assert response.name == "name_value" + assert response.uid == "uid_value" + assert response.display_name == "display_name_value" + assert response.state == cloud_speech.CustomClass.State.ACTIVE + assert response.etag == "etag_value" + assert response.reconciling is True + assert response.kms_key_name == "kms_key_name_value" + assert response.kms_key_version_name == "kms_key_version_name_value" + + +def test_get_custom_class_rest_required_fields( + request_type=cloud_speech.GetCustomClassRequest, +): + transport_class = transports.SpeechRestTransport + + 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, + including_default_value_fields=False, + use_integers_for_enums=False, + ) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get_custom_class._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_custom_class._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 = SpeechClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = cloud_speech.CustomClass() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force 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 + + pb_return_value = cloud_speech.CustomClass.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.get_custom_class(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_get_custom_class_rest_unset_required_fields(): + transport = transports.SpeechRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.get_custom_class._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_custom_class_rest_interceptors(null_interceptor): + transport = transports.SpeechRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SpeechRestInterceptor(), + ) + client = SpeechClient(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.SpeechRestInterceptor, "post_get_custom_class" + ) as post, mock.patch.object( + transports.SpeechRestInterceptor, "pre_get_custom_class" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = cloud_speech.GetCustomClassRequest.pb( + cloud_speech.GetCustomClassRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = cloud_speech.CustomClass.to_json( + cloud_speech.CustomClass() + ) + + request = cloud_speech.GetCustomClassRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = cloud_speech.CustomClass() + + client.get_custom_class( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_custom_class_rest_bad_request( + transport: str = "rest", request_type=cloud_speech.GetCustomClassRequest +): + client = SpeechClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/customClasses/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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_custom_class(request) + + +def test_get_custom_class_rest_flattened(): + client = SpeechClient( + 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 = cloud_speech.CustomClass() + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/customClasses/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 + pb_return_value = cloud_speech.CustomClass.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.get_custom_class(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v2/{name=projects/*/locations/*/customClasses/*}" + % client.transport._host, + args[1], + ) + + +def test_get_custom_class_rest_flattened_error(transport: str = "rest"): + client = SpeechClient( + credentials=ga_credentials.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_custom_class( + cloud_speech.GetCustomClassRequest(), + name="name_value", + ) + + +def test_get_custom_class_rest_error(): + client = SpeechClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + cloud_speech.UpdateCustomClassRequest, + dict, + ], +) +def test_update_custom_class_rest(request_type): + client = SpeechClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = { + "custom_class": { + "name": "projects/sample1/locations/sample2/customClasses/sample3" + } + } + request_init["custom_class"] = { + "name": "projects/sample1/locations/sample2/customClasses/sample3", + "uid": "uid_value", + "display_name": "display_name_value", + "items": [{"value": "value_value"}], + "state": 2, + "create_time": {"seconds": 751, "nanos": 543}, + "update_time": {}, + "delete_time": {}, + "expire_time": {}, + "annotations": {}, + "etag": "etag_value", + "reconciling": True, + "kms_key_name": "kms_key_name_value", + "kms_key_version_name": "kms_key_version_name_value", + } + 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 = 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 + response = client.update_custom_class(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_update_custom_class_rest_required_fields( + request_type=cloud_speech.UpdateCustomClassRequest, +): + transport_class = transports.SpeechRestTransport + + request_init = {} + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False, + ) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).update_custom_class._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).update_custom_class._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "update_mask", + "validate_only", + ) + ) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + + client = SpeechClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "patch", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.update_custom_class(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_update_custom_class_rest_unset_required_fields(): + transport = transports.SpeechRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.update_custom_class._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "updateMask", + "validateOnly", + ) + ) + & set(("customClass",)) + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_custom_class_rest_interceptors(null_interceptor): + transport = transports.SpeechRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SpeechRestInterceptor(), + ) + client = SpeechClient(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.SpeechRestInterceptor, "post_update_custom_class" + ) as post, mock.patch.object( + transports.SpeechRestInterceptor, "pre_update_custom_class" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = cloud_speech.UpdateCustomClassRequest.pb( + cloud_speech.UpdateCustomClassRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson( + operations_pb2.Operation() + ) + + request = cloud_speech.UpdateCustomClassRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.update_custom_class( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_custom_class_rest_bad_request( + transport: str = "rest", request_type=cloud_speech.UpdateCustomClassRequest +): + client = SpeechClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = { + "custom_class": { + "name": "projects/sample1/locations/sample2/customClasses/sample3" + } + } + request_init["custom_class"] = { + "name": "projects/sample1/locations/sample2/customClasses/sample3", + "uid": "uid_value", + "display_name": "display_name_value", + "items": [{"value": "value_value"}], + "state": 2, + "create_time": {"seconds": 751, "nanos": 543}, + "update_time": {}, + "delete_time": {}, + "expire_time": {}, + "annotations": {}, + "etag": "etag_value", + "reconciling": True, + "kms_key_name": "kms_key_name_value", + "kms_key_version_name": "kms_key_version_name_value", + } + 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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.update_custom_class(request) + + +def test_update_custom_class_rest_flattened(): + client = SpeechClient( + 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 = { + "custom_class": { + "name": "projects/sample1/locations/sample2/customClasses/sample3" + } + } + + # get truthy value for each flattened field + mock_args = dict( + custom_class=cloud_speech.CustomClass(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 + + client.update_custom_class(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v2/{custom_class.name=projects/*/locations/*/customClasses/*}" + % client.transport._host, + args[1], + ) + + +def test_update_custom_class_rest_flattened_error(transport: str = "rest"): + client = SpeechClient( + credentials=ga_credentials.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_custom_class( + cloud_speech.UpdateCustomClassRequest(), + custom_class=cloud_speech.CustomClass(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +def test_update_custom_class_rest_error(): + client = SpeechClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + cloud_speech.DeleteCustomClassRequest, + dict, + ], +) +def test_delete_custom_class_rest(request_type): + client = SpeechClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/customClasses/sample3"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = 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 + response = client.delete_custom_class(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_delete_custom_class_rest_required_fields( + request_type=cloud_speech.DeleteCustomClassRequest, +): + transport_class = transports.SpeechRestTransport + + 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, + including_default_value_fields=False, + use_integers_for_enums=False, + ) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).delete_custom_class._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).delete_custom_class._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "allow_missing", + "etag", + "validate_only", + ) + ) + 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 = SpeechClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "delete", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.delete_custom_class(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_delete_custom_class_rest_unset_required_fields(): + transport = transports.SpeechRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.delete_custom_class._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "allowMissing", + "etag", + "validateOnly", + ) + ) + & set(("name",)) + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_custom_class_rest_interceptors(null_interceptor): + transport = transports.SpeechRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SpeechRestInterceptor(), + ) + client = SpeechClient(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.SpeechRestInterceptor, "post_delete_custom_class" + ) as post, mock.patch.object( + transports.SpeechRestInterceptor, "pre_delete_custom_class" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = cloud_speech.DeleteCustomClassRequest.pb( + cloud_speech.DeleteCustomClassRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson( + operations_pb2.Operation() + ) + + request = cloud_speech.DeleteCustomClassRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.delete_custom_class( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_delete_custom_class_rest_bad_request( + transport: str = "rest", request_type=cloud_speech.DeleteCustomClassRequest +): + client = SpeechClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/customClasses/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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.delete_custom_class(request) + + +def test_delete_custom_class_rest_flattened(): + client = SpeechClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/customClasses/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 + + client.delete_custom_class(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v2/{name=projects/*/locations/*/customClasses/*}" + % client.transport._host, + args[1], + ) + + +def test_delete_custom_class_rest_flattened_error(transport: str = "rest"): + client = SpeechClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.delete_custom_class( + cloud_speech.DeleteCustomClassRequest(), + name="name_value", + ) + + +def test_delete_custom_class_rest_error(): + client = SpeechClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + cloud_speech.UndeleteCustomClassRequest, + dict, + ], +) +def test_undelete_custom_class_rest(request_type): + client = SpeechClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/customClasses/sample3"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = 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 + response = client.undelete_custom_class(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_undelete_custom_class_rest_required_fields( + request_type=cloud_speech.UndeleteCustomClassRequest, +): + transport_class = transports.SpeechRestTransport + + 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, + including_default_value_fields=False, + use_integers_for_enums=False, + ) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).undelete_custom_class._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() + ).undelete_custom_class._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 = SpeechClient( + 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 + + response = client.undelete_custom_class(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_undelete_custom_class_rest_unset_required_fields(): + transport = transports.SpeechRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.undelete_custom_class._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_undelete_custom_class_rest_interceptors(null_interceptor): + transport = transports.SpeechRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SpeechRestInterceptor(), + ) + client = SpeechClient(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.SpeechRestInterceptor, "post_undelete_custom_class" + ) as post, mock.patch.object( + transports.SpeechRestInterceptor, "pre_undelete_custom_class" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = cloud_speech.UndeleteCustomClassRequest.pb( + cloud_speech.UndeleteCustomClassRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson( + operations_pb2.Operation() + ) + + request = cloud_speech.UndeleteCustomClassRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.undelete_custom_class( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_undelete_custom_class_rest_bad_request( + transport: str = "rest", request_type=cloud_speech.UndeleteCustomClassRequest +): + client = SpeechClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/customClasses/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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.undelete_custom_class(request) + + +def test_undelete_custom_class_rest_flattened(): + client = SpeechClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/customClasses/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 + + client.undelete_custom_class(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v2/{name=projects/*/locations/*/customClasses/*}:undelete" + % client.transport._host, + args[1], + ) + + +def test_undelete_custom_class_rest_flattened_error(transport: str = "rest"): + client = SpeechClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.undelete_custom_class( + cloud_speech.UndeleteCustomClassRequest(), + name="name_value", + ) + + +def test_undelete_custom_class_rest_error(): + client = SpeechClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + cloud_speech.CreatePhraseSetRequest, + dict, + ], +) +def test_create_phrase_set_rest(request_type): + client = SpeechClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2"} + request_init["phrase_set"] = { + "name": "name_value", + "uid": "uid_value", + "phrases": [{"value": "value_value", "boost": 0.551}], + "boost": 0.551, + "display_name": "display_name_value", + "state": 2, + "create_time": {"seconds": 751, "nanos": 543}, + "update_time": {}, + "delete_time": {}, + "expire_time": {}, + "annotations": {}, + "etag": "etag_value", + "reconciling": True, + "kms_key_name": "kms_key_name_value", + "kms_key_version_name": "kms_key_version_name_value", + } + 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 = 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 + response = client.create_phrase_set(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_create_phrase_set_rest_required_fields( + request_type=cloud_speech.CreatePhraseSetRequest, +): + transport_class = transports.SpeechRestTransport + + 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, + including_default_value_fields=False, + use_integers_for_enums=False, + ) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).create_phrase_set._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = "parent_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).create_phrase_set._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "phrase_set_id", + "validate_only", + ) + ) + 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 = SpeechClient( + 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 + + response = client.create_phrase_set(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_create_phrase_set_rest_unset_required_fields(): + transport = transports.SpeechRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.create_phrase_set._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "phraseSetId", + "validateOnly", + ) + ) + & set( + ( + "phraseSet", + "parent", + ) + ) + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_phrase_set_rest_interceptors(null_interceptor): + transport = transports.SpeechRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SpeechRestInterceptor(), + ) + client = SpeechClient(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.SpeechRestInterceptor, "post_create_phrase_set" + ) as post, mock.patch.object( + transports.SpeechRestInterceptor, "pre_create_phrase_set" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = cloud_speech.CreatePhraseSetRequest.pb( + cloud_speech.CreatePhraseSetRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson( + operations_pb2.Operation() + ) + + request = cloud_speech.CreatePhraseSetRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.create_phrase_set( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_create_phrase_set_rest_bad_request( + transport: str = "rest", request_type=cloud_speech.CreatePhraseSetRequest +): + client = SpeechClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2"} + request_init["phrase_set"] = { + "name": "name_value", + "uid": "uid_value", + "phrases": [{"value": "value_value", "boost": 0.551}], + "boost": 0.551, + "display_name": "display_name_value", + "state": 2, + "create_time": {"seconds": 751, "nanos": 543}, + "update_time": {}, + "delete_time": {}, + "expire_time": {}, + "annotations": {}, + "etag": "etag_value", + "reconciling": True, + "kms_key_name": "kms_key_name_value", + "kms_key_version_name": "kms_key_version_name_value", + } + 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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.create_phrase_set(request) + + +def test_create_phrase_set_rest_flattened(): + client = SpeechClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # get arguments that satisfy an http rule for this method + sample_request = {"parent": "projects/sample1/locations/sample2"} + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + phrase_set=cloud_speech.PhraseSet(name="name_value"), + phrase_set_id="phrase_set_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 + + client.create_phrase_set(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v2/{parent=projects/*/locations/*}/phraseSets" % client.transport._host, + args[1], + ) + + +def test_create_phrase_set_rest_flattened_error(transport: str = "rest"): + client = SpeechClient( + credentials=ga_credentials.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_phrase_set( + cloud_speech.CreatePhraseSetRequest(), + parent="parent_value", + phrase_set=cloud_speech.PhraseSet(name="name_value"), + phrase_set_id="phrase_set_id_value", + ) + + +def test_create_phrase_set_rest_error(): + client = SpeechClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + cloud_speech.ListPhraseSetsRequest, + dict, + ], +) +def test_list_phrase_sets_rest(request_type): + client = SpeechClient( + 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 = cloud_speech.ListPhraseSetsResponse( + next_page_token="next_page_token_value", + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = cloud_speech.ListPhraseSetsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.list_phrase_sets(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListPhraseSetsPager) + assert response.next_page_token == "next_page_token_value" + + +def test_list_phrase_sets_rest_required_fields( + request_type=cloud_speech.ListPhraseSetsRequest, +): + transport_class = transports.SpeechRestTransport + + 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, + including_default_value_fields=False, + use_integers_for_enums=False, + ) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).list_phrase_sets._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = "parent_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).list_phrase_sets._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "page_size", + "page_token", + "show_deleted", + ) + ) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + + client = SpeechClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = cloud_speech.ListPhraseSetsResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force 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 + + pb_return_value = cloud_speech.ListPhraseSetsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.list_phrase_sets(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_list_phrase_sets_rest_unset_required_fields(): + transport = transports.SpeechRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.list_phrase_sets._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "pageSize", + "pageToken", + "showDeleted", + ) + ) + & set(("parent",)) + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_phrase_sets_rest_interceptors(null_interceptor): + transport = transports.SpeechRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SpeechRestInterceptor(), + ) + client = SpeechClient(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.SpeechRestInterceptor, "post_list_phrase_sets" + ) as post, mock.patch.object( + transports.SpeechRestInterceptor, "pre_list_phrase_sets" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = cloud_speech.ListPhraseSetsRequest.pb( + cloud_speech.ListPhraseSetsRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = cloud_speech.ListPhraseSetsResponse.to_json( + cloud_speech.ListPhraseSetsResponse() + ) + + request = cloud_speech.ListPhraseSetsRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = cloud_speech.ListPhraseSetsResponse() + + client.list_phrase_sets( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_phrase_sets_rest_bad_request( + transport: str = "rest", request_type=cloud_speech.ListPhraseSetsRequest +): + client = SpeechClient( + 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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_phrase_sets(request) + + +def test_list_phrase_sets_rest_flattened(): + client = SpeechClient( + 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 = cloud_speech.ListPhraseSetsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {"parent": "projects/sample1/locations/sample2"} + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = cloud_speech.ListPhraseSetsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.list_phrase_sets(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v2/{parent=projects/*/locations/*}/phraseSets" % client.transport._host, + args[1], + ) + + +def test_list_phrase_sets_rest_flattened_error(transport: str = "rest"): + client = SpeechClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_phrase_sets( + cloud_speech.ListPhraseSetsRequest(), + parent="parent_value", + ) + + +def test_list_phrase_sets_rest_pager(transport: str = "rest"): + client = SpeechClient( + 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 = ( + cloud_speech.ListPhraseSetsResponse( + phrase_sets=[ + cloud_speech.PhraseSet(), + cloud_speech.PhraseSet(), + cloud_speech.PhraseSet(), + ], + next_page_token="abc", + ), + cloud_speech.ListPhraseSetsResponse( + phrase_sets=[], + next_page_token="def", + ), + cloud_speech.ListPhraseSetsResponse( + phrase_sets=[ + cloud_speech.PhraseSet(), + ], + next_page_token="ghi", + ), + cloud_speech.ListPhraseSetsResponse( + phrase_sets=[ + cloud_speech.PhraseSet(), + cloud_speech.PhraseSet(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple( + cloud_speech.ListPhraseSetsResponse.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_phrase_sets(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, cloud_speech.PhraseSet) for i in results) + + pages = list(client.list_phrase_sets(request=sample_request).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.parametrize( + "request_type", + [ + cloud_speech.GetPhraseSetRequest, + dict, + ], +) +def test_get_phrase_set_rest(request_type): + client = SpeechClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/phraseSets/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 = cloud_speech.PhraseSet( + name="name_value", + uid="uid_value", + boost=0.551, + display_name="display_name_value", + state=cloud_speech.PhraseSet.State.ACTIVE, + etag="etag_value", + reconciling=True, + kms_key_name="kms_key_name_value", + kms_key_version_name="kms_key_version_name_value", + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = cloud_speech.PhraseSet.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.get_phrase_set(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, cloud_speech.PhraseSet) + assert response.name == "name_value" + assert response.uid == "uid_value" + assert math.isclose(response.boost, 0.551, rel_tol=1e-6) + assert response.display_name == "display_name_value" + assert response.state == cloud_speech.PhraseSet.State.ACTIVE + assert response.etag == "etag_value" + assert response.reconciling is True + assert response.kms_key_name == "kms_key_name_value" + assert response.kms_key_version_name == "kms_key_version_name_value" + + +def test_get_phrase_set_rest_required_fields( + request_type=cloud_speech.GetPhraseSetRequest, +): + transport_class = transports.SpeechRestTransport + + 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, + including_default_value_fields=False, + use_integers_for_enums=False, + ) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get_phrase_set._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_phrase_set._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 = SpeechClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = cloud_speech.PhraseSet() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force 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 + + pb_return_value = cloud_speech.PhraseSet.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.get_phrase_set(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_get_phrase_set_rest_unset_required_fields(): + transport = transports.SpeechRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.get_phrase_set._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_phrase_set_rest_interceptors(null_interceptor): + transport = transports.SpeechRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SpeechRestInterceptor(), + ) + client = SpeechClient(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.SpeechRestInterceptor, "post_get_phrase_set" + ) as post, mock.patch.object( + transports.SpeechRestInterceptor, "pre_get_phrase_set" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = cloud_speech.GetPhraseSetRequest.pb( + cloud_speech.GetPhraseSetRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = cloud_speech.PhraseSet.to_json( + cloud_speech.PhraseSet() + ) + + request = cloud_speech.GetPhraseSetRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = cloud_speech.PhraseSet() + + client.get_phrase_set( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_phrase_set_rest_bad_request( + transport: str = "rest", request_type=cloud_speech.GetPhraseSetRequest +): + client = SpeechClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/phraseSets/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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_phrase_set(request) + + +def test_get_phrase_set_rest_flattened(): + client = SpeechClient( + 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 = cloud_speech.PhraseSet() + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/phraseSets/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 + pb_return_value = cloud_speech.PhraseSet.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.get_phrase_set(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v2/{name=projects/*/locations/*/phraseSets/*}" % client.transport._host, + args[1], + ) + + +def test_get_phrase_set_rest_flattened_error(transport: str = "rest"): + client = SpeechClient( + credentials=ga_credentials.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_phrase_set( + cloud_speech.GetPhraseSetRequest(), + name="name_value", + ) + + +def test_get_phrase_set_rest_error(): + client = SpeechClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + cloud_speech.UpdatePhraseSetRequest, + dict, + ], +) +def test_update_phrase_set_rest(request_type): + client = SpeechClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = { + "phrase_set": {"name": "projects/sample1/locations/sample2/phraseSets/sample3"} + } + request_init["phrase_set"] = { + "name": "projects/sample1/locations/sample2/phraseSets/sample3", + "uid": "uid_value", + "phrases": [{"value": "value_value", "boost": 0.551}], + "boost": 0.551, + "display_name": "display_name_value", + "state": 2, + "create_time": {"seconds": 751, "nanos": 543}, + "update_time": {}, + "delete_time": {}, + "expire_time": {}, + "annotations": {}, + "etag": "etag_value", + "reconciling": True, + "kms_key_name": "kms_key_name_value", + "kms_key_version_name": "kms_key_version_name_value", + } + 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 = 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 + response = client.update_phrase_set(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_update_phrase_set_rest_required_fields( + request_type=cloud_speech.UpdatePhraseSetRequest, +): + transport_class = transports.SpeechRestTransport + + request_init = {} + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False, + ) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).update_phrase_set._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).update_phrase_set._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "update_mask", + "validate_only", + ) + ) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + + client = SpeechClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "patch", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.update_phrase_set(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_update_phrase_set_rest_unset_required_fields(): + transport = transports.SpeechRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.update_phrase_set._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "updateMask", + "validateOnly", + ) + ) + & set(("phraseSet",)) + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_phrase_set_rest_interceptors(null_interceptor): + transport = transports.SpeechRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SpeechRestInterceptor(), + ) + client = SpeechClient(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.SpeechRestInterceptor, "post_update_phrase_set" + ) as post, mock.patch.object( + transports.SpeechRestInterceptor, "pre_update_phrase_set" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = cloud_speech.UpdatePhraseSetRequest.pb( + cloud_speech.UpdatePhraseSetRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson( + operations_pb2.Operation() + ) + + request = cloud_speech.UpdatePhraseSetRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.update_phrase_set( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_phrase_set_rest_bad_request( + transport: str = "rest", request_type=cloud_speech.UpdatePhraseSetRequest +): + client = SpeechClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = { + "phrase_set": {"name": "projects/sample1/locations/sample2/phraseSets/sample3"} + } + request_init["phrase_set"] = { + "name": "projects/sample1/locations/sample2/phraseSets/sample3", + "uid": "uid_value", + "phrases": [{"value": "value_value", "boost": 0.551}], + "boost": 0.551, + "display_name": "display_name_value", + "state": 2, + "create_time": {"seconds": 751, "nanos": 543}, + "update_time": {}, + "delete_time": {}, + "expire_time": {}, + "annotations": {}, + "etag": "etag_value", + "reconciling": True, + "kms_key_name": "kms_key_name_value", + "kms_key_version_name": "kms_key_version_name_value", + } + 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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.update_phrase_set(request) + + +def test_update_phrase_set_rest_flattened(): + client = SpeechClient( + 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 = { + "phrase_set": { + "name": "projects/sample1/locations/sample2/phraseSets/sample3" + } + } + + # get truthy value for each flattened field + mock_args = dict( + phrase_set=cloud_speech.PhraseSet(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 + + client.update_phrase_set(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v2/{phrase_set.name=projects/*/locations/*/phraseSets/*}" + % client.transport._host, + args[1], + ) + + +def test_update_phrase_set_rest_flattened_error(transport: str = "rest"): + client = SpeechClient( + credentials=ga_credentials.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_phrase_set( + cloud_speech.UpdatePhraseSetRequest(), + phrase_set=cloud_speech.PhraseSet(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +def test_update_phrase_set_rest_error(): + client = SpeechClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + cloud_speech.DeletePhraseSetRequest, + dict, + ], +) +def test_delete_phrase_set_rest(request_type): + client = SpeechClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/phraseSets/sample3"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = 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 + response = client.delete_phrase_set(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_delete_phrase_set_rest_required_fields( + request_type=cloud_speech.DeletePhraseSetRequest, +): + transport_class = transports.SpeechRestTransport + + 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, + including_default_value_fields=False, + use_integers_for_enums=False, + ) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).delete_phrase_set._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_phrase_set._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "allow_missing", + "etag", + "validate_only", + ) + ) + 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 = SpeechClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "delete", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.delete_phrase_set(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_delete_phrase_set_rest_unset_required_fields(): + transport = transports.SpeechRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.delete_phrase_set._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "allowMissing", + "etag", + "validateOnly", + ) + ) + & set(("name",)) + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_phrase_set_rest_interceptors(null_interceptor): + transport = transports.SpeechRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SpeechRestInterceptor(), + ) + client = SpeechClient(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.SpeechRestInterceptor, "post_delete_phrase_set" + ) as post, mock.patch.object( + transports.SpeechRestInterceptor, "pre_delete_phrase_set" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = cloud_speech.DeletePhraseSetRequest.pb( + cloud_speech.DeletePhraseSetRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson( + operations_pb2.Operation() + ) + + request = cloud_speech.DeletePhraseSetRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.delete_phrase_set( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_delete_phrase_set_rest_bad_request( + transport: str = "rest", request_type=cloud_speech.DeletePhraseSetRequest +): + client = SpeechClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/phraseSets/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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.delete_phrase_set(request) + + +def test_delete_phrase_set_rest_flattened(): + client = SpeechClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/phraseSets/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 + + client.delete_phrase_set(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v2/{name=projects/*/locations/*/phraseSets/*}" % client.transport._host, + args[1], + ) + + +def test_delete_phrase_set_rest_flattened_error(transport: str = "rest"): + client = SpeechClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.delete_phrase_set( + cloud_speech.DeletePhraseSetRequest(), + name="name_value", + ) + + +def test_delete_phrase_set_rest_error(): + client = SpeechClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + cloud_speech.UndeletePhraseSetRequest, + dict, + ], +) +def test_undelete_phrase_set_rest(request_type): + client = SpeechClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/phraseSets/sample3"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = 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 + response = client.undelete_phrase_set(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_undelete_phrase_set_rest_required_fields( + request_type=cloud_speech.UndeletePhraseSetRequest, +): + transport_class = transports.SpeechRestTransport + + 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, + including_default_value_fields=False, + use_integers_for_enums=False, + ) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).undelete_phrase_set._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() + ).undelete_phrase_set._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 = SpeechClient( + 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 + + response = client.undelete_phrase_set(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_undelete_phrase_set_rest_unset_required_fields(): + transport = transports.SpeechRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.undelete_phrase_set._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_undelete_phrase_set_rest_interceptors(null_interceptor): + transport = transports.SpeechRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SpeechRestInterceptor(), + ) + client = SpeechClient(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.SpeechRestInterceptor, "post_undelete_phrase_set" + ) as post, mock.patch.object( + transports.SpeechRestInterceptor, "pre_undelete_phrase_set" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = cloud_speech.UndeletePhraseSetRequest.pb( + cloud_speech.UndeletePhraseSetRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson( + operations_pb2.Operation() + ) + + request = cloud_speech.UndeletePhraseSetRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.undelete_phrase_set( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_undelete_phrase_set_rest_bad_request( + transport: str = "rest", request_type=cloud_speech.UndeletePhraseSetRequest +): + client = SpeechClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/phraseSets/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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.undelete_phrase_set(request) + + +def test_undelete_phrase_set_rest_flattened(): + client = SpeechClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/phraseSets/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 + + client.undelete_phrase_set(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v2/{name=projects/*/locations/*/phraseSets/*}:undelete" + % client.transport._host, + args[1], + ) + + +def test_undelete_phrase_set_rest_flattened_error(transport: str = "rest"): + client = SpeechClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.undelete_phrase_set( + cloud_speech.UndeletePhraseSetRequest(), + name="name_value", + ) + + +def test_undelete_phrase_set_rest_error(): + client = SpeechClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +def test_streaming_recognize_rest_error(): + client = SpeechClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # Since a `google.api.http` annotation is required for using a rest transport + # method, this should error. + with pytest.raises(NotImplementedError) as not_implemented_error: + client.streaming_recognize({}) + assert "Method StreamingRecognize is not available over REST transport" in str( + not_implemented_error.value + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.SpeechGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = SpeechClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.SpeechGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = SpeechClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.SpeechGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = SpeechClient( + client_options=options, + transport=transport, + ) + + # It is an error to provide an api_key and a credential. + options = mock.Mock() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = SpeechClient( + client_options=options, credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.SpeechGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = SpeechClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.SpeechGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = SpeechClient(transport=transport) + assert client.transport is transport + + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.SpeechGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.SpeechGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.SpeechGrpcTransport, + transports.SpeechGrpcAsyncIOTransport, + transports.SpeechRestTransport, + ], +) +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() + + +@pytest.mark.parametrize( + "transport_name", + [ + "grpc", + "rest", + ], +) +def test_transport_kind(transport_name): + transport = SpeechClient.get_transport_class(transport_name)( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert transport.kind == transport_name + + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = SpeechClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.SpeechGrpcTransport, + ) + + +def test_speech_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.SpeechTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json", + ) + + +def test_speech_base_transport(): + # Instantiate the base transport. + with mock.patch( + "google.cloud.speech_v2.services.speech.transports.SpeechTransport.__init__" + ) as Transport: + Transport.return_value = None + transport = transports.SpeechTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + "create_recognizer", + "list_recognizers", + "get_recognizer", + "update_recognizer", + "delete_recognizer", + "undelete_recognizer", + "recognize", + "streaming_recognize", + "batch_recognize", + "get_config", + "update_config", + "create_custom_class", + "list_custom_classes", + "get_custom_class", + "update_custom_class", + "delete_custom_class", + "undelete_custom_class", + "create_phrase_set", + "list_phrase_sets", + "get_phrase_set", + "update_phrase_set", + "delete_phrase_set", + "undelete_phrase_set", + "get_operation", + "cancel_operation", + "delete_operation", + "list_operations", + ) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + with pytest.raises(NotImplementedError): + transport.close() + + # Additionally, the LRO client (a property) should + # also raise NotImplementedError + with pytest.raises(NotImplementedError): + transport.operations_client + + # Catch all for all remaining methods and properties + remainder = [ + "kind", + ] + for r in remainder: + with pytest.raises(NotImplementedError): + getattr(transport, r)() + + +def test_speech_base_transport_with_credentials_file(): + # Instantiate the base transport with a credentials file with mock.patch.object( google.auth, "load_credentials_from_file", autospec=True ) as load_creds, mock.patch( @@ -7006,6 +13805,7 @@ def test_speech_transport_auth_adc(transport_class): [ transports.SpeechGrpcTransport, transports.SpeechGrpcAsyncIOTransport, + transports.SpeechRestTransport, ], ) def test_speech_transport_auth_gdch_credentials(transport_class): @@ -7100,11 +13900,40 @@ def test_speech_grpc_transport_client_cert_source_for_mtls(transport_class): ) +def test_speech_http_transport_client_cert_source_for_mtls(): + cred = ga_credentials.AnonymousCredentials() + with mock.patch( + "google.auth.transport.requests.AuthorizedSession.configure_mtls_channel" + ) as mock_configure_mtls_channel: + transports.SpeechRestTransport( + credentials=cred, client_cert_source_for_mtls=client_cert_source_callback + ) + mock_configure_mtls_channel.assert_called_once_with(client_cert_source_callback) + + +def test_speech_rest_lro_client(): + client = SpeechClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + transport = client.transport + + # Ensure that we have a api-core operations client. + assert isinstance( + transport.operations_client, + operations_v1.AbstractOperationsClient, + ) + + # Ensure that subsequent calls to the property send the exact same object. + assert transport.operations_client is transport.operations_client + + @pytest.mark.parametrize( "transport_name", [ "grpc", "grpc_asyncio", + "rest", ], ) def test_speech_host_no_port(transport_name): @@ -7115,7 +13944,11 @@ def test_speech_host_no_port(transport_name): ), transport=transport_name, ) - assert client.transport._host == ("speech.googleapis.com:443") + assert client.transport._host == ( + "speech.googleapis.com:443" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://speech.googleapis.com" + ) @pytest.mark.parametrize( @@ -7123,6 +13956,7 @@ def test_speech_host_no_port(transport_name): [ "grpc", "grpc_asyncio", + "rest", ], ) def test_speech_host_with_port(transport_name): @@ -7133,7 +13967,99 @@ def test_speech_host_with_port(transport_name): ), transport=transport_name, ) - assert client.transport._host == ("speech.googleapis.com:8000") + assert client.transport._host == ( + "speech.googleapis.com:8000" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://speech.googleapis.com:8000" + ) + + +@pytest.mark.parametrize( + "transport_name", + [ + "rest", + ], +) +def test_speech_client_transport_session_collision(transport_name): + creds1 = ga_credentials.AnonymousCredentials() + creds2 = ga_credentials.AnonymousCredentials() + client1 = SpeechClient( + credentials=creds1, + transport=transport_name, + ) + client2 = SpeechClient( + credentials=creds2, + transport=transport_name, + ) + session1 = client1.transport.create_recognizer._session + session2 = client2.transport.create_recognizer._session + assert session1 != session2 + session1 = client1.transport.list_recognizers._session + session2 = client2.transport.list_recognizers._session + assert session1 != session2 + session1 = client1.transport.get_recognizer._session + session2 = client2.transport.get_recognizer._session + assert session1 != session2 + session1 = client1.transport.update_recognizer._session + session2 = client2.transport.update_recognizer._session + assert session1 != session2 + session1 = client1.transport.delete_recognizer._session + session2 = client2.transport.delete_recognizer._session + assert session1 != session2 + session1 = client1.transport.undelete_recognizer._session + session2 = client2.transport.undelete_recognizer._session + assert session1 != session2 + session1 = client1.transport.recognize._session + session2 = client2.transport.recognize._session + assert session1 != session2 + session1 = client1.transport.streaming_recognize._session + session2 = client2.transport.streaming_recognize._session + assert session1 != session2 + session1 = client1.transport.batch_recognize._session + session2 = client2.transport.batch_recognize._session + assert session1 != session2 + session1 = client1.transport.get_config._session + session2 = client2.transport.get_config._session + assert session1 != session2 + session1 = client1.transport.update_config._session + session2 = client2.transport.update_config._session + assert session1 != session2 + session1 = client1.transport.create_custom_class._session + session2 = client2.transport.create_custom_class._session + assert session1 != session2 + session1 = client1.transport.list_custom_classes._session + session2 = client2.transport.list_custom_classes._session + assert session1 != session2 + session1 = client1.transport.get_custom_class._session + session2 = client2.transport.get_custom_class._session + assert session1 != session2 + session1 = client1.transport.update_custom_class._session + session2 = client2.transport.update_custom_class._session + assert session1 != session2 + session1 = client1.transport.delete_custom_class._session + session2 = client2.transport.delete_custom_class._session + assert session1 != session2 + session1 = client1.transport.undelete_custom_class._session + session2 = client2.transport.undelete_custom_class._session + assert session1 != session2 + session1 = client1.transport.create_phrase_set._session + session2 = client2.transport.create_phrase_set._session + assert session1 != session2 + session1 = client1.transport.list_phrase_sets._session + session2 = client2.transport.list_phrase_sets._session + assert session1 != session2 + session1 = client1.transport.get_phrase_set._session + session2 = client2.transport.get_phrase_set._session + assert session1 != session2 + session1 = client1.transport.update_phrase_set._session + session2 = client2.transport.update_phrase_set._session + assert session1 != session2 + session1 = client1.transport.delete_phrase_set._session + session2 = client2.transport.delete_phrase_set._session + assert session1 != session2 + session1 = client1.transport.undelete_phrase_set._session + session2 = client2.transport.undelete_phrase_set._session + assert session1 != session2 def test_speech_grpc_transport_channel(): @@ -7596,6 +14522,238 @@ async def test_transport_close_async(): close.assert_called_once() +def test_cancel_operation_rest_bad_request( + transport: str = "rest", request_type=operations_pb2.CancelOperationRequest +): + client = SpeechClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + request = request_type() + request = json_format.ParseDict( + {"name": "projects/sample1/locations/sample2/operations/sample3"}, request + ) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.cancel_operation(request) + + +@pytest.mark.parametrize( + "request_type", + [ + operations_pb2.CancelOperationRequest, + dict, + ], +) +def test_cancel_operation_rest(request_type): + client = SpeechClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request_init = {"name": "projects/sample1/locations/sample2/operations/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 = None + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = "{}" + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.cancel_operation(request) + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_operation_rest_bad_request( + transport: str = "rest", request_type=operations_pb2.DeleteOperationRequest +): + client = SpeechClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + request = request_type() + request = json_format.ParseDict( + {"name": "projects/sample1/locations/sample2/operations/sample3"}, request + ) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.delete_operation(request) + + +@pytest.mark.parametrize( + "request_type", + [ + operations_pb2.DeleteOperationRequest, + dict, + ], +) +def test_delete_operation_rest(request_type): + client = SpeechClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request_init = {"name": "projects/sample1/locations/sample2/operations/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 = None + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = "{}" + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.delete_operation(request) + + # Establish that the response is the type that we expect. + assert response is None + + +def test_get_operation_rest_bad_request( + transport: str = "rest", request_type=operations_pb2.GetOperationRequest +): + client = SpeechClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + request = request_type() + request = json_format.ParseDict( + {"name": "projects/sample1/locations/sample2/operations/sample3"}, request + ) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_operation(request) + + +@pytest.mark.parametrize( + "request_type", + [ + operations_pb2.GetOperationRequest, + dict, + ], +) +def test_get_operation_rest(request_type): + client = SpeechClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request_init = {"name": "projects/sample1/locations/sample2/operations/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() + + # 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 + + response = client.get_operation(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.Operation) + + +def test_list_operations_rest_bad_request( + transport: str = "rest", request_type=operations_pb2.ListOperationsRequest +): + client = SpeechClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + request = request_type() + request = json_format.ParseDict( + {"name": "projects/sample1/locations/sample2"}, request + ) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_operations(request) + + +@pytest.mark.parametrize( + "request_type", + [ + operations_pb2.ListOperationsRequest, + dict, + ], +) +def test_list_operations_rest(request_type): + client = SpeechClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request_init = {"name": "projects/sample1/locations/sample2"} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.ListOperationsResponse() + + # 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 + + response = client.list_operations(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.ListOperationsResponse) + + def test_delete_operation(transport: str = "grpc"): client = SpeechClient( credentials=ga_credentials.AnonymousCredentials(), @@ -8166,6 +15324,7 @@ async def test_list_operations_from_dict_async(): def test_transport_close(): transports = { + "rest": "_session", "grpc": "_grpc_channel", } @@ -8183,6 +15342,7 @@ def test_transport_close(): def test_client_ctx(): transports = [ + "rest", "grpc", ] for transport in transports: