forked from googleapis/google-cloud-python
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathtest_client.py
More file actions
352 lines (283 loc) · 13.1 KB
/
Copy pathtest_client.py
File metadata and controls
352 lines (283 loc) · 13.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
# Copyright 2016 Google Inc.
#
# 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.
import unittest
class TestClient(unittest.TestCase):
SAMPLE_RATE = 16000
HINTS = ['hi']
AUDIO_SOURCE_URI = 'gs://sample-bucket/sample-recording.flac'
AUDIO_CONTENT = '/9j/4QNURXhpZgAASUkq'
def _getTargetClass(self):
from google.cloud.speech.client import Client
return Client
def _makeOne(self, *args, **kw):
return self._getTargetClass()(*args, **kw)
def test_ctor(self):
from google.cloud.speech.connection import Connection
creds = _Credentials()
http = object()
client = self._makeOne(credentials=creds, http=http)
self.assertIsInstance(client.connection, Connection)
self.assertTrue(client.connection.credentials is creds)
self.assertTrue(client.connection.http is http)
def test_ctor_use_gax_preset(self):
creds = _Credentials()
http = object()
client = self._makeOne(credentials=creds, http=http, use_gax=True)
self.assertTrue(client._use_gax)
def test_create_sample_from_client(self):
from google.cloud import speech
from google.cloud.speech.sample import Sample
credentials = _Credentials()
client = self._makeOne(credentials=credentials)
sample = client.sample(source_uri=self.AUDIO_SOURCE_URI,
encoding=speech.Encoding.FLAC,
sample_rate=self.SAMPLE_RATE)
self.assertIsInstance(sample, Sample)
self.assertEqual(sample.source_uri, self.AUDIO_SOURCE_URI)
self.assertEqual(sample.sample_rate, self.SAMPLE_RATE)
self.assertEqual(sample.encoding, speech.Encoding.FLAC)
content_sample = client.sample(content=self.AUDIO_CONTENT,
encoding=speech.Encoding.FLAC,
sample_rate=self.SAMPLE_RATE)
self.assertEqual(content_sample.content, self.AUDIO_CONTENT)
self.assertEqual(content_sample.sample_rate, self.SAMPLE_RATE)
self.assertEqual(content_sample.encoding, speech.Encoding.FLAC)
def test_sync_recognize_content_with_optional_params_no_gax(self):
from base64 import b64encode
from google.cloud._helpers import _to_bytes
from google.cloud._helpers import _bytes_to_unicode
from google.cloud._testing import _Monkey
from google.cloud.speech import client as MUT
from google.cloud import speech
from google.cloud.speech.sample import Sample
from google.cloud.speech.transcript import Transcript
from unit_tests._fixtures import SYNC_RECOGNIZE_RESPONSE
_AUDIO_CONTENT = _to_bytes(self.AUDIO_CONTENT)
_B64_AUDIO_CONTENT = _bytes_to_unicode(b64encode(_AUDIO_CONTENT))
RETURNED = SYNC_RECOGNIZE_RESPONSE
REQUEST = {
'config': {
'encoding': 'FLAC',
'maxAlternatives': 2,
'sampleRate': 16000,
'speechContext': {
'phrases': [
'hi',
]
},
'languageCode': 'EN',
'profanityFilter': True,
},
'audio': {
'content': _B64_AUDIO_CONTENT,
}
}
credentials = _Credentials()
client = self._makeOne(credentials=credentials, use_gax=False)
client.connection = _Connection(RETURNED)
encoding = speech.Encoding.FLAC
sample = Sample(content=self.AUDIO_CONTENT, encoding=encoding,
sample_rate=self.SAMPLE_RATE)
with _Monkey(MUT, _USE_GAX=False):
response = client.sync_recognize(sample,
language_code='EN',
max_alternatives=2,
profanity_filter=True,
speech_context=self.HINTS)
self.assertEqual(len(client.connection._requested), 1)
req = client.connection._requested[0]
self.assertEqual(len(req), 3)
self.assertEqual(req['data'], REQUEST)
self.assertEqual(req['method'], 'POST')
self.assertEqual(req['path'], 'speech:syncrecognize')
alternative = SYNC_RECOGNIZE_RESPONSE['results'][0]['alternatives'][0]
expected = Transcript.from_api_repr(alternative)
self.assertEqual(len(response), 1)
self.assertIsInstance(response[0], Transcript)
self.assertEqual(response[0].transcript, expected.transcript)
self.assertEqual(response[0].confidence, expected.confidence)
def test_sync_recognize_source_uri_without_optional_params_no_gax(self):
from google.cloud._testing import _Monkey
from google.cloud.speech import client as MUT
from google.cloud import speech
from google.cloud.speech.sample import Sample
from google.cloud.speech.transcript import Transcript
from unit_tests._fixtures import SYNC_RECOGNIZE_RESPONSE
RETURNED = SYNC_RECOGNIZE_RESPONSE
REQUEST = {
'config': {
'encoding': 'FLAC',
'sampleRate': 16000,
},
'audio': {
'uri': self.AUDIO_SOURCE_URI,
}
}
credentials = _Credentials()
client = self._makeOne(credentials=credentials, use_gax=False)
client.connection = _Connection(RETURNED)
encoding = speech.Encoding.FLAC
sample = Sample(source_uri=self.AUDIO_SOURCE_URI, encoding=encoding,
sample_rate=self.SAMPLE_RATE)
with _Monkey(MUT, _USE_GAX=False):
response = client.sync_recognize(sample)
self.assertEqual(len(client.connection._requested), 1)
req = client.connection._requested[0]
self.assertEqual(len(req), 3)
self.assertEqual(req['data'], REQUEST)
self.assertEqual(req['method'], 'POST')
self.assertEqual(req['path'], 'speech:syncrecognize')
expected = Transcript.from_api_repr(
SYNC_RECOGNIZE_RESPONSE['results'][0]['alternatives'][0])
self.assertEqual(len(response), 1)
self.assertIsInstance(response[0], Transcript)
self.assertEqual(response[0].transcript, expected.transcript)
self.assertEqual(response[0].confidence, expected.confidence)
def test_sync_recognize_with_empty_results_no_gax(self):
from google.cloud._testing import _Monkey
from google.cloud.speech import client as MUT
from google.cloud import speech
from google.cloud.speech.sample import Sample
from unit_tests._fixtures import SYNC_RECOGNIZE_EMPTY_RESPONSE
credentials = _Credentials()
client = self._makeOne(credentials=credentials, use_gax=False)
client.connection = _Connection(SYNC_RECOGNIZE_EMPTY_RESPONSE)
with self.assertRaises(ValueError):
with _Monkey(MUT, _USE_GAX=False):
sample = Sample(source_uri=self.AUDIO_SOURCE_URI,
encoding=speech.Encoding.FLAC,
sample_rate=self.SAMPLE_RATE)
client.sync_recognize(sample)
def test_sync_recognize_with_empty_results_gax(self):
from google.cloud._testing import _Monkey
from google.cloud.speech import _gax as MUT
from google.cloud import speech
from google.cloud.speech.sample import Sample
credentials = _Credentials()
client = self._makeOne(credentials=credentials, use_gax=True)
client.connection = _Connection()
with self.assertRaises(ValueError):
mock_no_results = _MockGAPICSpeechAPI
mock_no_results._results = []
with _Monkey(MUT, SpeechApi=mock_no_results):
sample = Sample(source_uri=self.AUDIO_SOURCE_URI,
encoding=speech.Encoding.FLAC,
sample_rate=self.SAMPLE_RATE)
client.sync_recognize(sample)
def test_sync_recognize_with_gax(self):
from google.cloud import speech
from google.cloud.speech import _gax as MUT
from google.cloud._testing import _Monkey
creds = _Credentials()
client = self._makeOne(credentials=creds, use_gax=True)
client.connection = _Connection()
client._speech_api = None
mock_no_results = _MockGAPICSpeechAPI
mock_no_results._results = [_MockGAPICSyncResult()]
with _Monkey(MUT, SpeechApi=_MockGAPICSpeechAPI):
sample = client.sample(source_uri=self.AUDIO_SOURCE_URI,
encoding=speech.Encoding.FLAC,
sample_rate=self.SAMPLE_RATE)
results = client.sync_recognize(sample)
self.assertEqual(results[0].transcript,
_MockGAPICAlternative.transcript)
self.assertEqual(results[0].confidence,
_MockGAPICAlternative.confidence)
def test_async_supported_encodings(self):
from google.cloud import speech
from google.cloud.speech.sample import Sample
credentials = _Credentials()
client = self._makeOne(credentials=credentials)
client.connection = _Connection({})
sample = Sample(source_uri=self.AUDIO_SOURCE_URI,
encoding=speech.Encoding.FLAC,
sample_rate=self.SAMPLE_RATE)
with self.assertRaises(ValueError):
client.async_recognize(sample)
def test_async_recognize(self):
from unit_tests._fixtures import ASYNC_RECOGNIZE_RESPONSE
from google.cloud import speech
from google.cloud.speech.operation import Operation
from google.cloud.speech.sample import Sample
RETURNED = ASYNC_RECOGNIZE_RESPONSE
credentials = _Credentials()
client = self._makeOne(credentials=credentials)
client.connection = _Connection(RETURNED)
sample = Sample(source_uri=self.AUDIO_SOURCE_URI,
encoding=speech.Encoding.LINEAR16,
sample_rate=self.SAMPLE_RATE)
operation = client.async_recognize(sample)
self.assertIsInstance(operation, Operation)
self.assertFalse(operation.complete)
self.assertIsNone(operation.metadata)
def test_speech_api_with_gax(self):
from google.cloud.speech import _gax as MUT
from google.cloud._testing import _Monkey
from google.cloud.speech.client import GAPICSpeechAPI
creds = _Credentials()
client = self._makeOne(credentials=creds, use_gax=True)
with _Monkey(MUT, SpeechApi=_MockGAPICSpeechAPI):
self.assertIsNone(client._speech_api)
self.assertIsInstance(client.speech_api, GAPICSpeechAPI)
def test_speech_api_without_gax(self):
from google.cloud.speech.client import _JSONSpeechAPI
creds = _Credentials()
client = self._makeOne(credentials=creds, use_gax=False)
self.assertIsNone(client._speech_api)
self.assertIsInstance(client.speech_api, _JSONSpeechAPI)
def test_speech_api_preset(self):
creds = _Credentials()
client = self._makeOne(credentials=creds)
fake_api = object()
client._speech_api = fake_api
self.assertIs(client.speech_api, fake_api)
class _MockGAPICAlternative(object):
transcript = 'testing 1 2 3'
confidence = 0.95234356
class _MockGAPICSyncResult(object):
alternatives = [_MockGAPICAlternative()]
class _MockGAPICSpeechResponse(object):
error = None
endpointer_type = None
results = []
result_index = 0
class _MockGAPICSpeechAPI(object):
_requests = None
_response = _MockGAPICSpeechResponse()
_results = [_MockGAPICSyncResult()]
def sync_recognize(self, config, audio):
self.config = config
self.audio = audio
mock_response = self._response
mock_response.results = self._results
return mock_response
class _Credentials(object):
_scopes = ('https://www.googleapis.com/auth/cloud-platform',)
def __init__(self, authorized=None):
self._authorized = authorized
self._create_scoped_calls = 0
@staticmethod
def create_scoped_required():
return True
def create_scoped(self, scope):
self._scopes = scope
return self
class _Connection(object):
def __init__(self, *responses):
self._responses = responses
self._requested = []
def api_request(self, **kw):
self._requested.append(kw)
response, self._responses = self._responses[0], self._responses[1:]
return response