From 9f7e1acdaa5a86c25c3d9f9bc6cd84a55b31b83f Mon Sep 17 00:00:00 2001 From: Thomas Schultz Date: Tue, 28 Feb 2017 17:55:36 -0500 Subject: [PATCH 1/2] Add test file for Result class. --- speech/unit_tests/test_result.py | 60 ++++++++++++++++++++++++++++++++ 1 file changed, 60 insertions(+) create mode 100644 speech/unit_tests/test_result.py diff --git a/speech/unit_tests/test_result.py b/speech/unit_tests/test_result.py new file mode 100644 index 000000000000..3e9ba36140d5 --- /dev/null +++ b/speech/unit_tests/test_result.py @@ -0,0 +1,60 @@ +# Copyright 2017 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 TestResult(unittest.TestCase): + @staticmethod + def _get_target_class(): + from google.cloud.speech.result import Result + + return Result + + def _make_one(self, *args, **kw): + return self._get_target_class()(*args, **kw) + + def test_ctor(self): + result = self._make_one([]) + self.assertIsInstance(result, self._get_target_class()) + + def test_from_pb(self): + from google.cloud.proto.speech.v1beta1 import cloud_speech_pb2 + + confidence = 0.625 + transcript = 'this is a test transcript' + alternative = cloud_speech_pb2.SpeechRecognitionAlternative( + transcript=transcript, confidence=confidence) + result_pb = cloud_speech_pb2.SpeechRecognitionResult( + alternatives=[alternative]) + + result = self._get_target_class().from_pb(result_pb) + self.assertEqual(result.confidence, confidence) + self.assertEqual(result.transcript, transcript) + + def test_from_api_repr(self): + confidence = 0.625 + transcript = 'this is a test' + response = { + 'alternatives': [ + { + 'confidence': confidence, + 'transcript': transcript, + }, + ], + } + + result = self._get_target_class().from_api_repr(response) + self.assertEqual(result.confidence, confidence) + self.assertEqual(result.transcript, transcript) From 8e5cd1ebd6ce4dd0a4315a1d8caad8429c867199 Mon Sep 17 00:00:00 2001 From: Thomas Schultz Date: Tue, 28 Feb 2017 17:55:51 -0500 Subject: [PATCH 2/2] Clean up formatting and docstrings. --- speech/google/cloud/speech/_gax.py | 6 +- speech/google/cloud/speech/result.py | 6 +- speech/unit_tests/_fixtures.py | 4 +- speech/unit_tests/test__gax.py | 93 ++++------ speech/unit_tests/test__http.py | 7 +- speech/unit_tests/test_client.py | 259 ++++++++++++++------------- speech/unit_tests/test_operation.py | 7 +- speech/unit_tests/test_sample.py | 62 ++++--- 8 files changed, 219 insertions(+), 225 deletions(-) diff --git a/speech/google/cloud/speech/_gax.py b/speech/google/cloud/speech/_gax.py index 963420f54028..da822f8356cc 100644 --- a/speech/google/cloud/speech/_gax.py +++ b/speech/google/cloud/speech/_gax.py @@ -39,7 +39,11 @@ class GAPICSpeechAPI(object): - """Manage calls through GAPIC wrappers to the Speech API.""" + """Manage calls through GAPIC wrappers to the Speech API. + + :type client: `~google.cloud.core.client.Client` + :param client: Instance of ``Client`. + """ def __init__(self, client=None): self._client = client credentials = self._client._credentials diff --git a/speech/google/cloud/speech/result.py b/speech/google/cloud/speech/result.py index 82ae472a4f39..83d4f629abfd 100644 --- a/speech/google/cloud/speech/result.py +++ b/speech/google/cloud/speech/result.py @@ -34,7 +34,7 @@ def __init__(self, alternatives): def from_pb(cls, result): """Factory: construct instance of ``Result``. - :type result: :class:`~google.cloud.grpc.speech.v1beta1\ + :type result: :class:`~google.cloud.proto.speech.v1beta1\ .cloud_speech_pb2.SpeechRecognitionResult` :param result: Instance of ``SpeechRecognitionResult`` protobuf. @@ -50,7 +50,7 @@ def from_api_repr(cls, result): """Factory: construct instance of ``Result``. :type result: dict - :param result: Dictionary of a :class:`~google.cloud.grpc.speech.\ + :param result: Dictionary of a :class:`~google.cloud.proto.speech.\ v1beta1.cloud_speech_pb2.SpeechRecognitionResult` :rtype: :class:`~google.cloud.speech.result.Result` @@ -101,7 +101,7 @@ def __init__(self, alternatives, is_final=False, stability=0.0): def from_pb(cls, response): """Factory: construct instance of ``StreamingSpeechResult``. - :type response: :class:`~google.cloud.grpc.speech.v1beta1\ + :type response: :class:`~google.cloud.proto.speech.v1beta1\ .cloud_speech_pb2.StreamingRecognizeResult` :param response: Instance of ``StreamingRecognizeResult`` protobuf. diff --git a/speech/unit_tests/_fixtures.py b/speech/unit_tests/_fixtures.py index 7980ed862038..c193960d9137 100644 --- a/speech/unit_tests/_fixtures.py +++ b/speech/unit_tests/_fixtures.py @@ -30,7 +30,7 @@ } ASYNC_RECOGNIZE_RESPONSE = { - 'name': '123456789' + 'name': '123456789', } OPERATION_COMPLETE_RESPONSE = { @@ -51,7 +51,7 @@ 'alternatives': [ { 'transcript': 'how old is the Brooklyn Bridge', - 'confidence': 0.98267895 + 'confidence': 0.98267895, }, ], }, diff --git a/speech/unit_tests/test__gax.py b/speech/unit_tests/test__gax.py index 8c7efea77bb1..e5d7624a2378 100644 --- a/speech/unit_tests/test__gax.py +++ b/speech/unit_tests/test__gax.py @@ -50,39 +50,24 @@ def test_constructor(self, mocked_stub, mocked_cls, mocked_channel): from google.cloud.speech._gax import OPERATIONS_API_HOST credentials = _make_credentials() - mock_cnxn = mock.Mock( - credentials=credentials, - spec=['credentials'], - ) + mock_cnxn = mock.Mock(credentials=credentials, spec=['credentials']) mock_client = mock.Mock( - _connection=mock_cnxn, - _credentials=credentials, - spec=['_connection', '_credentials'], - ) + _connection=mock_cnxn, _credentials=credentials, + spec=['_connection', '_credentials']) speech_api = self._make_one(mock_client) self.assertIs(speech_api._client, mock_client) - self.assertIs( - speech_api._gapic_api, - mocked_cls.return_value, - ) + self.assertIs(speech_api._gapic_api, mocked_cls.return_value) mocked_stub.assert_called_once_with( - mock_cnxn.credentials, - DEFAULT_USER_AGENT, - operations_grpc.OperationsStub, - OPERATIONS_API_HOST, - ) + mock_cnxn.credentials, DEFAULT_USER_AGENT, + operations_grpc.OperationsStub, OPERATIONS_API_HOST) mocked_cls.assert_called_once_with( - channel=mock.sentinel.channel, - lib_name='gccl', - lib_version=__version__, - ) + channel=mock.sentinel.channel, lib_name='gccl', + lib_version=__version__) mocked_channel.assert_called_once_with( - mock_cnxn.credentials, - DEFAULT_USER_AGENT, - mocked_cls.SERVICE_ADDRESS, - ) + mock_cnxn.credentials, DEFAULT_USER_AGENT, + mocked_cls.SERVICE_ADDRESS) class TestSpeechGAXMakeRequests(unittest.TestCase): @@ -95,13 +80,11 @@ def _call_fut(self, sample, language_code, max_alternatives, interim_results): from google.cloud.speech._gax import _make_streaming_request - return _make_streaming_request(sample=sample, - language_code=language_code, - max_alternatives=max_alternatives, - profanity_filter=profanity_filter, - speech_context=speech_context, - single_utterance=single_utterance, - interim_results=interim_results) + return _make_streaming_request( + sample=sample, language_code=language_code, + max_alternatives=max_alternatives, + profanity_filter=profanity_filter, speech_context=speech_context, + single_utterance=single_utterance, interim_results=interim_results) def test_ctor(self): from google.cloud import speech @@ -110,9 +93,9 @@ def test_ctor(self): RecognitionConfig, SpeechContext, StreamingRecognitionConfig, StreamingRecognizeRequest) - sample = Sample(content=self.AUDIO_CONTENT, - encoding=speech.Encoding.FLAC, - sample_rate=self.SAMPLE_RATE) + sample = Sample( + content=self.AUDIO_CONTENT, encoding=speech.Encoding.FLAC, + sample_rate=self.SAMPLE_RATE) language_code = 'US-en' max_alternatives = 2 profanity_filter = True @@ -120,10 +103,9 @@ def test_ctor(self): single_utterance = True interim_results = False - streaming_request = self._call_fut(sample, language_code, - max_alternatives, profanity_filter, - speech_context, single_utterance, - interim_results) + streaming_request = self._call_fut( + sample, language_code, max_alternatives, profanity_filter, + speech_context, single_utterance, interim_results) self.assertIsInstance(streaming_request, StreamingRecognizeRequest) # This isn't set by _make_streaming_request(). @@ -131,8 +113,8 @@ def test_ctor(self): # The following requests can only have `audio_content` set. self.assertEqual(streaming_request.audio_content, b'') - self.assertIsInstance(streaming_request.streaming_config, - StreamingRecognitionConfig) + self.assertIsInstance( + streaming_request.streaming_config, StreamingRecognitionConfig) streaming_config = streaming_request.streaming_config self.assertTrue(streaming_config.single_utterance) self.assertFalse(streaming_config.interim_results) @@ -156,13 +138,11 @@ def _call_fut(self, sample, language_code, max_alternatives, interim_results): from google.cloud.speech._gax import _stream_requests - return _stream_requests(sample=sample, - language_code=language_code, - max_alternatives=max_alternatives, - profanity_filter=profanity_filter, - speech_context=speech_context, - single_utterance=single_utterance, - interim_results=interim_results) + return _stream_requests( + sample=sample, language_code=language_code, + max_alternatives=max_alternatives, + profanity_filter=profanity_filter, speech_context=speech_context, + single_utterance=single_utterance, interim_results=interim_results) def test_stream_requests(self): from io import BytesIO @@ -171,19 +151,18 @@ def test_stream_requests(self): from google.cloud.proto.speech.v1beta1.cloud_speech_pb2 import ( StreamingRecognitionConfig, StreamingRecognizeRequest) - sample = Sample(stream=BytesIO(self.AUDIO_CONTENT), - encoding=speech.Encoding.FLAC, - sample_rate=self.SAMPLE_RATE) + sample = Sample( + stream=BytesIO(self.AUDIO_CONTENT), encoding=speech.Encoding.FLAC, + sample_rate=self.SAMPLE_RATE) language_code = 'US-en' max_alternatives = 2 profanity_filter = True speech_context = self.HINTS single_utterance = True interim_results = False - streaming_requests = self._call_fut(sample, language_code, - max_alternatives, profanity_filter, - speech_context, single_utterance, - interim_results) + streaming_requests = self._call_fut( + sample, language_code, max_alternatives, profanity_filter, + speech_context, single_utterance, interim_results) all_requests = [] for streaming_request in streaming_requests: self.assertIsInstance(streaming_request, StreamingRecognizeRequest) @@ -198,5 +177,5 @@ def test_stream_requests(self): # The following requests can only have `audio_content` set. self.assertEqual(config_request.audio_content, b'') self.assertEqual(streaming_request.audio_content, self.AUDIO_CONTENT) - self.assertIsInstance(config_request.streaming_config, - StreamingRecognitionConfig) + self.assertIsInstance( + config_request.streaming_config, StreamingRecognitionConfig) diff --git a/speech/unit_tests/test__http.py b/speech/unit_tests/test__http.py index a590a71ab6a5..fd39428ffdbb 100644 --- a/speech/unit_tests/test__http.py +++ b/speech/unit_tests/test__http.py @@ -63,8 +63,5 @@ def test_extra_headers(self): } expected_uri = conn.build_api_url('/rainbow') http.request.assert_called_once_with( - body=req_data, - headers=expected_headers, - method='GET', - uri=expected_uri, - ) + body=req_data, headers=expected_headers, method='GET', + uri=expected_uri) diff --git a/speech/unit_tests/test_client.py b/speech/unit_tests/test_client.py index 18e4ec24a88d..8aa83daeecf0 100644 --- a/speech/unit_tests/test_client.py +++ b/speech/unit_tests/test_client.py @@ -104,17 +104,17 @@ def test_create_sample_from_client(self): credentials = _make_credentials() client = self._make_one(credentials=credentials) - sample = client.sample(source_uri=self.AUDIO_SOURCE_URI, - encoding=speech.Encoding.FLAC, - sample_rate=self.SAMPLE_RATE) + 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) + 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) @@ -129,9 +129,8 @@ def test_sync_recognize_content_with_optional_params_no_gax(self): from google.cloud.speech.result import Result from unit_tests._fixtures import SYNC_RECOGNIZE_RESPONSE - _B64_AUDIO_CONTENT = _bytes_to_unicode(b64encode(self.AUDIO_CONTENT)) - RETURNED = SYNC_RECOGNIZE_RESPONSE - REQUEST = { + _b64_audio_content = _bytes_to_unicode(b64encode(self.AUDIO_CONTENT)) + request = { 'config': { 'encoding': 'FLAC', 'maxAlternatives': 2, @@ -145,38 +144,39 @@ def test_sync_recognize_content_with_optional_params_no_gax(self): 'profanityFilter': True, }, 'audio': { - 'content': _B64_AUDIO_CONTENT, + 'content': _b64_audio_content, } } credentials = _make_credentials() client = self._make_one(credentials=credentials, use_gax=False) speech_api = client.speech_api - connection = _Connection(RETURNED) + connection = _Connection(SYNC_RECOGNIZE_RESPONSE) speech_api._connection = connection encoding = speech.Encoding.FLAC - sample = client.sample(content=self.AUDIO_CONTENT, encoding=encoding, - sample_rate=self.SAMPLE_RATE) + sample = client.sample( + content=self.AUDIO_CONTENT, encoding=encoding, + sample_rate=self.SAMPLE_RATE) - response = sample.sync_recognize(language_code='EN', - max_alternatives=2, - profanity_filter=True, - speech_context=self.HINTS) + response = sample.sync_recognize( + language_code='EN', max_alternatives=2, profanity_filter=True, + speech_context=self.HINTS) self.assertEqual(len(connection._requested), 1) req = connection._requested[0] self.assertEqual(len(req), 3) - self.assertEqual(req['data'], REQUEST) + 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 = Alternative.from_api_repr(alternative) self.assertEqual(len(response), 1) - self.assertIsInstance(response[0], Result) - self.assertEqual(len(response[0].alternatives), 1) - alternative = response[0].alternatives[0] + result = response[0] + self.assertIsInstance(result, Result) + self.assertEqual(len(result.alternatives), 1) + alternative = result.alternatives[0] self.assertEqual(alternative.transcript, expected.transcript) self.assertEqual(alternative.confidence, expected.confidence) @@ -186,43 +186,45 @@ def test_sync_recognize_source_uri_without_optional_params_no_gax(self): from google.cloud.speech.result import Result from unit_tests._fixtures import SYNC_RECOGNIZE_RESPONSE - RETURNED = SYNC_RECOGNIZE_RESPONSE - REQUEST = { + request = { 'config': { 'encoding': 'FLAC', 'sampleRate': 16000, }, 'audio': { 'uri': self.AUDIO_SOURCE_URI, - } + }, } credentials = _make_credentials() client = self._make_one(credentials=credentials, use_gax=False) speech_api = client.speech_api - connection = _Connection(RETURNED) + connection = _Connection(SYNC_RECOGNIZE_RESPONSE) speech_api._connection = connection encoding = speech.Encoding.FLAC - sample = client.sample(source_uri=self.AUDIO_SOURCE_URI, - encoding=encoding, sample_rate=self.SAMPLE_RATE) + sample = client.sample( + source_uri=self.AUDIO_SOURCE_URI, encoding=encoding, + sample_rate=self.SAMPLE_RATE) response = [i for i in sample.sync_recognize()] self.assertEqual(len(connection._requested), 1) req = connection._requested[0] self.assertEqual(len(req), 3) - self.assertEqual(req['data'], REQUEST) + self.assertEqual(req['data'], request) self.assertEqual(req['method'], 'POST') self.assertEqual(req['path'], 'speech:syncrecognize') expected = Alternative.from_api_repr( SYNC_RECOGNIZE_RESPONSE['results'][0]['alternatives'][0]) self.assertEqual(len(response), 1) - self.assertIsInstance(response[0], Result) - self.assertEqual(len(response[0].alternatives), 1) - alternative = response[0].alternatives[0] + result = response[0] + self.assertIsInstance(result, Result) + self.assertEqual(len(result.alternatives), 1) + + alternative = result.alternatives[0] self.assertEqual(alternative.transcript, expected.transcript) self.assertEqual(alternative.confidence, expected.confidence) @@ -235,9 +237,9 @@ def test_sync_recognize_with_empty_results_no_gax(self): speech_api = client.speech_api speech_api._connection = _Connection(SYNC_RECOGNIZE_EMPTY_RESPONSE) - sample = client.sample(source_uri=self.AUDIO_SOURCE_URI, - encoding=speech.Encoding.FLAC, - sample_rate=self.SAMPLE_RATE) + sample = client.sample( + source_uri=self.AUDIO_SOURCE_URI, encoding=speech.Encoding.FLAC, + sample_rate=self.SAMPLE_RATE) with self.assertRaises(ValueError): next(sample.sync_recognize()) @@ -260,8 +262,8 @@ def make_channel(*args): return channel_obj def speech_api(channel=None, **kwargs): - return _MockGAPICSpeechAPI(response=_make_sync_response(), - channel=channel, **kwargs) + return _MockGAPICSpeechAPI( + response=_make_sync_response(), channel=channel, **kwargs) host = 'foo.apis.invalid' speech_api.SERVICE_ADDRESS = host @@ -277,9 +279,9 @@ def speech_api(channel=None, **kwargs): channel_args, [(credentials, _gax.DEFAULT_USER_AGENT, host)]) - sample = client.sample(source_uri=self.AUDIO_SOURCE_URI, - encoding=speech.Encoding.FLAC, - sample_rate=self.SAMPLE_RATE) + sample = client.sample( + source_uri=self.AUDIO_SOURCE_URI, encoding=speech.Encoding.FLAC, + sample_rate=self.SAMPLE_RATE) with self.assertRaises(ValueError): next(sample.sync_recognize()) @@ -312,15 +314,15 @@ def make_channel(*args): def speech_api(channel=None, **kwargs): return _MockGAPICSpeechAPI( - response=_make_sync_response(result), - channel=channel, **kwargs) + response=_make_sync_response(result), channel=channel, + **kwargs) host = 'foo.apis.invalid' speech_api.SERVICE_ADDRESS = host - sample = client.sample(source_uri=self.AUDIO_SOURCE_URI, - encoding=speech.Encoding.FLAC, - sample_rate=self.SAMPLE_RATE) + sample = client.sample( + source_uri=self.AUDIO_SOURCE_URI, encoding=speech.Encoding.FLAC, + sample_rate=self.SAMPLE_RATE) with _Monkey(_gax, SpeechClient=speech_api, make_secure_channel=make_channel): @@ -335,17 +337,18 @@ def speech_api(channel=None, **kwargs): results = [i for i in sample.sync_recognize()] self.assertEqual(len(results), 1) + result = results[0] self.assertEqual(len(results[0].alternatives), 2) - self.assertEqual(results[0].transcript, - results[0].alternatives[0].transcript, - alternatives[0]['transcript']) - self.assertEqual(results[0].confidence, - results[0].alternatives[0].confidence, - alternatives[0]['confidence']) - self.assertEqual(results[0].alternatives[1].transcript, - alternatives[1]['transcript']) - self.assertEqual(results[0].alternatives[1].confidence, - alternatives[1]['confidence']) + self.assertEqual( + result.transcript, result.alternatives[0].transcript, + alternatives[0]['transcript']) + self.assertEqual( + result.confidence, result.alternatives[0].confidence, + alternatives[0]['confidence']) + self.assertEqual( + result.alternatives[1].transcript, alternatives[1]['transcript']) + self.assertEqual( + result.alternatives[1].confidence, alternatives[1]['confidence']) def test_async_supported_encodings(self): from google.cloud import speech @@ -353,9 +356,9 @@ def test_async_supported_encodings(self): credentials = _make_credentials() client = self._make_one(credentials=credentials, use_gax=True) - sample = client.sample(source_uri=self.AUDIO_SOURCE_URI, - encoding=speech.Encoding.FLAC, - sample_rate=self.SAMPLE_RATE) + sample = client.sample( + source_uri=self.AUDIO_SOURCE_URI, encoding=speech.Encoding.FLAC, + sample_rate=self.SAMPLE_RATE) with self.assertRaises(ValueError): sample.async_recognize() @@ -371,14 +374,14 @@ def test_async_recognize_no_gax(self): speech_api = client.speech_api speech_api._connection = _Connection(RETURNED) - sample = client.sample(source_uri=self.AUDIO_SOURCE_URI, - encoding=speech.Encoding.LINEAR16, - sample_rate=self.SAMPLE_RATE) + sample = client.sample( + encoding=speech.Encoding.LINEAR16, sample_rate=self.SAMPLE_RATE, + source_uri=self.AUDIO_SOURCE_URI) operation = sample.async_recognize() self.assertIsInstance(operation, Operation) self.assertIs(operation.client, client) - self.assertEqual(operation.caller_metadata, - {'request_type': 'AsyncRecognize'}) + self.assertEqual( + operation.caller_metadata, {'request_type': 'AsyncRecognize'}) self.assertFalse(operation.complete) self.assertIsNone(operation.metadata) @@ -390,8 +393,7 @@ def test_async_recognize_with_gax(self): from google.cloud.speech.operation import Operation credentials = _make_credentials() - client = self._make_one(credentials=credentials, - use_gax=True) + client = self._make_one(credentials=credentials, use_gax=True) client._credentials = credentials channel_args = [] @@ -401,9 +403,9 @@ def make_channel(*args): channel_args.append(args) return channel_obj - sample = client.sample(source_uri=self.AUDIO_SOURCE_URI, - encoding=speech.Encoding.LINEAR16, - sample_rate=self.SAMPLE_RATE) + sample = client.sample( + encoding=speech.Encoding.LINEAR16, sample_rate=self.SAMPLE_RATE, + source_uri=self.AUDIO_SOURCE_URI) def speech_api(channel=None, **kwargs): return _MockGAPICSpeechAPI(channel=channel, **kwargs) @@ -432,9 +434,9 @@ def test_streaming_depends_on_gax(self): credentials = _make_credentials() client = self._make_one(credentials=credentials, use_gax=False) - sample = client.sample(content=self.AUDIO_CONTENT, - encoding=speech.Encoding.LINEAR16, - sample_rate=self.SAMPLE_RATE) + sample = client.sample( + content=self.AUDIO_CONTENT, encoding=speech.Encoding.LINEAR16, + sample_rate=self.SAMPLE_RATE) with self.assertRaises(EnvironmentError): list(sample.streaming_recognize()) @@ -468,9 +470,9 @@ def speech_api(channel=None, **kwargs): stream.close() self.assertTrue(stream.closed) - sample = client.sample(stream=stream, - encoding=Encoding.LINEAR16, - sample_rate=self.SAMPLE_RATE) + sample = client.sample( + stream=stream, encoding=Encoding.LINEAR16, + sample_rate=self.SAMPLE_RATE) with _Monkey(_gax, SpeechClient=speech_api, make_secure_channel=make_channel): @@ -503,11 +505,11 @@ def test_stream_recognize_interim_results(self): first_response = _make_streaming_response( _make_streaming_result([], is_final=False, stability=0.314453125)) second_response = _make_streaming_response( - _make_streaming_result(alternatives, is_final=False, - stability=0.28125)) + _make_streaming_result( + alternatives, is_final=False, stability=0.28125)) last_response = _make_streaming_response( - _make_streaming_result(alternatives, is_final=True, - stability=0.4375)) + _make_streaming_result( + alternatives, is_final=True, stability=0.4375)) responses = [first_response, second_response, last_response] channel_args = [] @@ -518,8 +520,8 @@ def make_channel(*args): return channel_obj def speech_api(channel=None, **kwargs): - return _MockGAPICSpeechAPI(channel=channel, response=responses, - **kwargs) + return _MockGAPICSpeechAPI( + channel=channel, response=responses, **kwargs) host = 'foo.apis.invalid' speech_api.SERVICE_ADDRESS = host @@ -528,37 +530,45 @@ def speech_api(channel=None, **kwargs): make_secure_channel=make_channel): client._speech_api = _gax.GAPICSpeechAPI(client) - sample = client.sample(stream=stream, - encoding=Encoding.LINEAR16, - sample_rate=self.SAMPLE_RATE) + sample = client.sample( + stream=stream, encoding=Encoding.LINEAR16, + sample_rate=self.SAMPLE_RATE) results = list(sample.streaming_recognize(interim_results=True)) self.assertEqual(len(results), 3) - self.assertIsInstance(results[0], StreamingSpeechResult) - self.assertEqual(results[0].alternatives, []) - self.assertFalse(results[0].is_final) - self.assertEqual(results[0].stability, 0.314453125) - self.assertEqual(results[1].stability, 0.28125) - self.assertFalse(results[1].is_final) - self.assertEqual(results[1].transcript, - results[1].alternatives[0].transcript, - alternatives[0]['transcript']) - self.assertEqual(results[1].confidence, - results[1].alternatives[0].confidence, - alternatives[0]['confidence']) - self.assertEqual(results[1].alternatives[1].transcript, - alternatives[1]['transcript']) - self.assertEqual(results[1].alternatives[1].confidence, - alternatives[1]['confidence']) - self.assertTrue(results[2].is_final) - self.assertEqual(results[2].stability, 0.4375) - self.assertEqual(results[2].transcript, - results[2].alternatives[0].transcript, - alternatives[0]['transcript']) - self.assertEqual(results[2].confidence, - results[2].alternatives[0].confidence, - alternatives[0]['confidence']) + for result in results: + self.assertIsInstance(result, StreamingSpeechResult) + + result = results[0] + self.assertEqual(result.alternatives, []) + self.assertFalse(result.is_final) + self.assertEqual(result.stability, 0.314453125) + + result_two = results[1] + self.assertEqual(result_two.stability, 0.28125) + self.assertFalse(result_two.is_final) + self.assertEqual( + result_two.transcript, result_two.alternatives[0].transcript, + alternatives[0]['transcript']) + self.assertEqual( + result_two.confidence, result_two.alternatives[0].confidence, + alternatives[0]['confidence']) + self.assertEqual( + result_two.alternatives[1].transcript, + alternatives[1]['transcript']) + self.assertEqual( + result_two.alternatives[1].confidence, + alternatives[1]['confidence']) + result_three = results[2] + self.assertTrue(result_three.is_final) + self.assertEqual(result_three.stability, 0.4375) + self.assertEqual( + result_three.transcript, result_three.alternatives[0].transcript, + alternatives[0]['transcript']) + self.assertEqual( + result_three.confidence, result_three.alternatives[0].confidence, + alternatives[0]['confidence']) def test_stream_recognize(self): from io import BytesIO @@ -595,8 +605,8 @@ def make_channel(*args): return channel_obj def speech_api(channel=None, **kwargs): - return _MockGAPICSpeechAPI(channel=channel, response=responses, - **kwargs) + return _MockGAPICSpeechAPI( + channel=channel, response=responses, **kwargs) host = 'foo.apis.invalid' speech_api.SERVICE_ADDRESS = host @@ -605,16 +615,17 @@ def speech_api(channel=None, **kwargs): make_secure_channel=make_channel): client._speech_api = _gax.GAPICSpeechAPI(client) - sample = client.sample(stream=stream, - encoding=Encoding.LINEAR16, - sample_rate=self.SAMPLE_RATE) + sample = client.sample( + stream=stream, encoding=Encoding.LINEAR16, + sample_rate=self.SAMPLE_RATE) results = list(sample.streaming_recognize()) self.assertEqual(len(results), 1) - self.assertEqual(results[0].alternatives[0].transcript, - alternatives[0]['transcript']) - self.assertEqual(results[0].alternatives[0].confidence, - alternatives[0]['confidence']) + result = results[0] + self.assertEqual( + result.alternatives[0].transcript, alternatives[0]['transcript']) + self.assertEqual( + result.alternatives[0].confidence, alternatives[0]['confidence']) def test_stream_recognize_no_results(self): from io import BytesIO @@ -639,8 +650,8 @@ def make_channel(*args): return channel_obj def speech_api(channel=None, **kwargs): - return _MockGAPICSpeechAPI(channel=channel, response=responses, - **kwargs) + return _MockGAPICSpeechAPI( + channel=channel, response=responses, **kwargs) host = 'foo.apis.invalid' speech_api.SERVICE_ADDRESS = host @@ -649,9 +660,9 @@ def speech_api(channel=None, **kwargs): make_secure_channel=make_channel): client._speech_api = _gax.GAPICSpeechAPI(client) - sample = client.sample(stream=stream, - encoding=Encoding.LINEAR16, - sample_rate=self.SAMPLE_RATE) + sample = client.sample( + stream=stream, encoding=Encoding.LINEAR16, + sample_rate=self.SAMPLE_RATE) results = list(sample.streaming_recognize()) self.assertEqual(results, []) @@ -685,8 +696,8 @@ def speech_api(channel=None, **kwargs): low_level = client.speech_api._gapic_api self.assertIsInstance(low_level, _MockGAPICSpeechAPI) self.assertIs(low_level._channel, channel_obj) - expected = (creds, _gax.DEFAULT_USER_AGENT, - low_level.SERVICE_ADDRESS) + expected = ( + creds, _gax.DEFAULT_USER_AGENT, low_level.SERVICE_ADDRESS) self.assertEqual(channel_args, [expected]) def test_speech_api_without_gax(self): @@ -730,8 +741,8 @@ def async_recognize(self, config, audio): self.config = config self.audio = audio operations_client = mock.Mock(spec=OperationsClient) - operation_future = _OperationFuture(Operation(), operations_client, - AsyncRecognizeResponse, {}) + operation_future = _OperationFuture( + Operation(), operations_client, AsyncRecognizeResponse, {}) return operation_future def sync_recognize(self, config, audio): diff --git a/speech/unit_tests/test_operation.py b/speech/unit_tests/test_operation.py index cbcac1a363a7..a5ed1d30e780 100644 --- a/speech/unit_tests/test_operation.py +++ b/speech/unit_tests/test_operation.py @@ -67,12 +67,11 @@ def _make_operation_pb(self, *results): ) type_url = 'type.googleapis.com/%s' % ( result_pb.DESCRIPTOR.full_name,) - any_pb = Any(type_url=type_url, - value=result_pb.SerializeToString()) + any_pb = Any( + type_url=type_url, value=result_pb.SerializeToString()) return operations_pb2.Operation( - name=self.OPERATION_NAME, - response=any_pb) + name=self.OPERATION_NAME, response=any_pb) def test__update_state_no_response(self): client = object() diff --git a/speech/unit_tests/test_sample.py b/speech/unit_tests/test_sample.py index 309de757bfaa..cbae7da80c8d 100644 --- a/speech/unit_tests/test_sample.py +++ b/speech/unit_tests/test_sample.py @@ -31,9 +31,9 @@ def _make_one(self, *args, **kw): def test_initialize_sample(self): from google.cloud.speech.encoding import Encoding - sample = self._make_one(source_uri=self.AUDIO_SOURCE_URI, - encoding=Encoding.FLAC, - sample_rate=self.SAMPLE_RATE) + sample = self._make_one( + source_uri=self.AUDIO_SOURCE_URI, encoding=Encoding.FLAC, + sample_rate=self.SAMPLE_RATE) self.assertEqual(sample.source_uri, self.AUDIO_SOURCE_URI) self.assertEqual(sample.encoding, Encoding.FLAC) self.assertEqual(sample.sample_rate, self.SAMPLE_RATE) @@ -42,17 +42,19 @@ def test_content_and_source_uri(self): from io import BytesIO with self.assertRaises(ValueError): - self._make_one(content='awefawagaeragere', - source_uri=self.AUDIO_SOURCE_URI) + self._make_one( + content='awefawagaeragere', source_uri=self.AUDIO_SOURCE_URI) with self.assertRaises(ValueError): - self._make_one(stream=BytesIO(b'awefawagaeragere'), - source_uri=self.AUDIO_SOURCE_URI) + self._make_one( + stream=BytesIO(b'awefawagaeragere'), + source_uri=self.AUDIO_SOURCE_URI) with self.assertRaises(ValueError): - self._make_one(content='awefawagaeragere', - stream=BytesIO(b'awefawagaeragere'), - source_uri=self.AUDIO_SOURCE_URI) + self._make_one( + content='awefawagaeragere', + stream=BytesIO(b'awefawagaeragere'), + source_uri=self.AUDIO_SOURCE_URI) def test_stream_property(self): from io import BytesIO @@ -60,8 +62,9 @@ def test_stream_property(self): data = b'abc 1 2 3 4' stream = BytesIO(data) - sample = self._make_one(stream=stream, encoding=Encoding.FLAC, - sample_rate=self.SAMPLE_RATE) + sample = self._make_one( + stream=stream, encoding=Encoding.FLAC, + sample_rate=self.SAMPLE_RATE) self.assertEqual(sample.stream, stream) self.assertEqual(sample.stream.read(), data) @@ -71,8 +74,9 @@ def test_bytes_converts_to_file_like_object(self): test_bytes = b'testing 1 2 3' - sample = Sample(content=test_bytes, encoding=speech.Encoding.FLAC, - sample_rate=self.SAMPLE_RATE) + sample = Sample( + content=test_bytes, encoding=speech.Encoding.FLAC, + sample_rate=self.SAMPLE_RATE) self.assertEqual(sample.content, test_bytes) self.assertEqual(sample.encoding, speech.Encoding.FLAC) self.assertEqual(sample.sample_rate, self.SAMPLE_RATE) @@ -81,15 +85,15 @@ def test_sample_rates(self): from google.cloud.speech.encoding import Encoding with self.assertRaises(ValueError): - self._make_one(source_uri=self.AUDIO_SOURCE_URI, - sample_rate=7999) + self._make_one( + source_uri=self.AUDIO_SOURCE_URI, sample_rate=7999) with self.assertRaises(ValueError): - self._make_one(source_uri=self.AUDIO_SOURCE_URI, - sample_rate=48001) + self._make_one( + source_uri=self.AUDIO_SOURCE_URI, sample_rate=48001) - sample = self._make_one(source_uri=self.AUDIO_SOURCE_URI, - sample_rate=self.SAMPLE_RATE, - encoding=Encoding.FLAC) + sample = self._make_one( + source_uri=self.AUDIO_SOURCE_URI, sample_rate=self.SAMPLE_RATE, + encoding=Encoding.FLAC) self.assertEqual(sample.sample_rate, self.SAMPLE_RATE) self.assertEqual(sample.encoding, Encoding.FLAC) @@ -97,13 +101,13 @@ def test_encoding(self): from google.cloud.speech.encoding import Encoding with self.assertRaises(ValueError): - self._make_one(source_uri=self.AUDIO_SOURCE_URI, - sample_rate=self.SAMPLE_RATE, - encoding='OGG') + self._make_one( + source_uri=self.AUDIO_SOURCE_URI, sample_rate=self.SAMPLE_RATE, + encoding='OGG') with self.assertRaises(ValueError): - self._make_one(source_uri=self.AUDIO_SOURCE_URI, - sample_rate=self.SAMPLE_RATE) - sample = self._make_one(source_uri=self.AUDIO_SOURCE_URI, - sample_rate=self.SAMPLE_RATE, - encoding=Encoding.FLAC) + self._make_one( + source_uri=self.AUDIO_SOURCE_URI, sample_rate=self.SAMPLE_RATE) + sample = self._make_one( + source_uri=self.AUDIO_SOURCE_URI, sample_rate=self.SAMPLE_RATE, + encoding=Encoding.FLAC) self.assertEqual(sample.encoding, Encoding.FLAC)