Spaces:
Runtime error
Runtime error
Download voice_control/tests/test_google_speech_provider.py from nifty-coder/stemsplit-backend: direct link, hf CLI and curl.
- Browser
- Download file 25.5 kB
-
https://huggingface.co/spaces/nifty-coder/stemsplit-backend/resolve/main/voice_control/tests/test_google_speech_provider.py
- Command line
-
hf download hf://spaces/nifty-coder/stemsplit-backend/voice_control/tests/test_google_speech_provider.py
-
curl -L -o test_google_speech_provider.py https://huggingface.co/spaces/nifty-coder/stemsplit-backend/resolve/main/voice_control/tests/test_google_speech_provider.py
25.5 kB
| """ | |
| Unit tests for GoogleSpeechProvider. | |
| This module contains comprehensive tests for the Google Speech-to-Text provider | |
| implementation, including quota management, error handling, and transcription | |
| functionality. | |
| """ | |
| import pytest | |
| import asyncio | |
| from unittest.mock import Mock, AsyncMock, patch, MagicMock | |
| from datetime import datetime, timezone, timedelta | |
| import json | |
| from voice_control.providers.google_speech_provider import ( | |
| GoogleSpeechProvider, | |
| create_google_speech_provider, | |
| GOOGLE_SPEECH_AVAILABLE | |
| ) | |
| from voice_control.models import ( | |
| ProviderConfig, | |
| ProviderType, | |
| TranscriptionResult, | |
| QuotaStatus, | |
| QuotaType, | |
| WordTimestamp | |
| ) | |
| from voice_control.exceptions import ( | |
| ProviderError, | |
| ProviderUnavailableError, | |
| ProviderAuthenticationError, | |
| UnsupportedFormatError, | |
| UnsupportedLanguageError, | |
| QuotaExceededError, | |
| RateLimitExceededError, | |
| TranscriptionError | |
| ) | |
| class TestGoogleSpeechProvider: | |
| """Test cases for GoogleSpeechProvider class.""" | |
| def mock_google_speech(self): | |
| """Mock Google Cloud Speech modules.""" | |
| with patch('voice_control.providers.google_speech_provider.GOOGLE_SPEECH_AVAILABLE', True): | |
| with patch('voice_control.providers.google_speech_provider.speech') as mock_speech: | |
| with patch('voice_control.providers.google_speech_provider.service_account') as mock_sa: | |
| with patch('voice_control.providers.google_speech_provider.google_exceptions') as mock_exc: | |
| # Setup mock speech client | |
| mock_client = Mock() | |
| mock_speech.SpeechClient.return_value = mock_client | |
| # Setup mock recognition config | |
| mock_config = Mock() | |
| mock_speech.RecognitionConfig.return_value = mock_config | |
| mock_speech.RecognitionConfig.AudioEncoding = Mock() | |
| mock_speech.RecognitionConfig.AudioEncoding.LINEAR16 = "LINEAR16" | |
| mock_speech.RecognitionConfig.AudioEncoding.FLAC = "FLAC" | |
| mock_speech.RecognitionConfig.AudioEncoding.MP3 = "MP3" | |
| mock_speech.RecognitionConfig.AudioEncoding.WEBM_OPUS = "WEBM_OPUS" | |
| # Setup mock audio | |
| mock_audio = Mock() | |
| mock_speech.RecognitionAudio.return_value = mock_audio | |
| # Setup mock streaming config | |
| mock_streaming_config = Mock() | |
| mock_speech.StreamingRecognitionConfig.return_value = mock_streaming_config | |
| # Setup mock streaming request | |
| mock_streaming_request = Mock() | |
| mock_speech.StreamingRecognizeRequest.return_value = mock_streaming_request | |
| yield { | |
| 'speech': mock_speech, | |
| 'service_account': mock_sa, | |
| 'exceptions': mock_exc, | |
| 'client': mock_client | |
| } | |
| def provider_config(self): | |
| """Create a test provider configuration.""" | |
| return ProviderConfig( | |
| name="test_google_speech", | |
| provider_type=ProviderType.GOOGLE_SPEECH, | |
| enabled=True, | |
| priority=2, | |
| free_tier_limits={ | |
| "audio_minutes_per_month": 60.0, | |
| "requests_per_minute": 1000, | |
| "requests_per_day": 50000 | |
| }, | |
| rate_limits={ | |
| "requests_per_minute": 1000, | |
| "requests_per_day": 50000 | |
| }, | |
| supported_formats=["wav", "flac", "mp3", "webm"], | |
| supported_languages=["en-US", "es-ES", "fr-FR"], | |
| cost_per_minute=0.006, | |
| api_credentials={ | |
| "service_account_key": '{"type": "service_account", "project_id": "test"}' | |
| }, | |
| timeout_seconds=60, | |
| max_retries=3 | |
| ) | |
| def sample_audio_data(self): | |
| """Create sample audio data for testing.""" | |
| return b'\x00\x01' * 8000 # 16KB of sample audio data | |
| def test_provider_initialization_without_library(self): | |
| """Test provider initialization when Google Speech library is not available.""" | |
| with patch('voice_control.providers.google_speech_provider.GOOGLE_SPEECH_AVAILABLE', False): | |
| config = ProviderConfig( | |
| name="test", | |
| provider_type=ProviderType.GOOGLE_SPEECH, | |
| enabled=True, | |
| priority=1, | |
| free_tier_limits={}, | |
| rate_limits={}, | |
| supported_formats=["wav"], | |
| supported_languages=["en-US"], | |
| cost_per_minute=0.0, | |
| api_credentials={} | |
| ) | |
| with pytest.raises(ImportError, match="Google Cloud Speech library not available"): | |
| GoogleSpeechProvider(config) | |
| def test_provider_initialization_invalid_type(self, mock_google_speech): | |
| """Test provider initialization with invalid provider type.""" | |
| config = ProviderConfig( | |
| name="invalid", | |
| provider_type=ProviderType.WEB_SPEECH_API, # Wrong type | |
| enabled=True, | |
| priority=1, | |
| free_tier_limits={}, | |
| rate_limits={}, | |
| supported_formats=["wav"], | |
| supported_languages=["en-US"], | |
| cost_per_minute=0.0, | |
| api_credentials={} | |
| ) | |
| with pytest.raises(ValueError, match="Invalid provider type"): | |
| GoogleSpeechProvider(config) | |
| async def test_provider_initialization_success(self, mock_google_speech, provider_config): | |
| """Test successful provider initialization.""" | |
| provider = GoogleSpeechProvider(provider_config) | |
| # Wait for initialization to complete | |
| await asyncio.sleep(0.1) | |
| assert provider.name == "test_google_speech" | |
| assert provider.provider_type == ProviderType.GOOGLE_SPEECH | |
| assert provider.config == provider_config | |
| def test_supports_format(self, mock_google_speech, provider_config): | |
| """Test format support checking.""" | |
| provider = GoogleSpeechProvider(provider_config) | |
| # Test supported formats | |
| assert provider.supports_format("wav") | |
| assert provider.supports_format("WAV") # Case insensitive | |
| assert provider.supports_format("flac") | |
| assert provider.supports_format("mp3") | |
| assert provider.supports_format("webm") | |
| # Test unsupported formats | |
| assert not provider.supports_format("aac") | |
| assert not provider.supports_format("m4a") | |
| assert not provider.supports_format("unknown") | |
| def test_supports_language(self, mock_google_speech, provider_config): | |
| """Test language support checking.""" | |
| provider = GoogleSpeechProvider(provider_config) | |
| # Test supported languages | |
| assert provider.supports_language("en-US") | |
| assert provider.supports_language("es-ES") | |
| assert provider.supports_language("fr-FR") | |
| assert provider.supports_language("de-DE") | |
| assert provider.supports_language("ja-JP") | |
| # Test unsupported languages | |
| assert not provider.supports_language("xx-XX") | |
| assert not provider.supports_language("invalid") | |
| async def test_estimate_cost_free_tier(self, mock_google_speech, provider_config): | |
| """Test cost estimation within free tier.""" | |
| provider = GoogleSpeechProvider(provider_config) | |
| # Test within free tier (60 minutes/month) | |
| cost = await provider.estimate_cost(1800) # 30 minutes | |
| assert cost == 0.0 | |
| # Test at free tier limit | |
| cost = await provider.estimate_cost(3600) # 60 minutes | |
| assert cost == 0.0 | |
| async def test_estimate_cost_exceeding_free_tier(self, mock_google_speech, provider_config): | |
| """Test cost estimation exceeding free tier.""" | |
| provider = GoogleSpeechProvider(provider_config) | |
| # Simulate some usage | |
| provider._usage_stats["audio_minutes_this_month"] = 50.0 # 50 minutes used | |
| # Test exceeding free tier | |
| cost = await provider.estimate_cost(1800) # 30 minutes (20 minutes over limit) | |
| expected_cost = 20.0 * 0.006 # 20 minutes at $0.006/minute | |
| assert abs(cost - expected_cost) < 0.001 | |
| async def test_check_health_success(self, mock_google_speech, provider_config): | |
| """Test successful health check.""" | |
| provider = GoogleSpeechProvider(provider_config) | |
| # Mock successful recognition | |
| mock_response = Mock() | |
| mock_google_speech['client'].recognize.return_value = mock_response | |
| health = await provider.check_health() | |
| assert health is True | |
| async def test_check_health_failure(self, mock_google_speech, provider_config): | |
| """Test health check failure.""" | |
| provider = GoogleSpeechProvider(provider_config) | |
| # Mock recognition failure | |
| mock_google_speech['client'].recognize.side_effect = Exception("API Error") | |
| health = await provider.check_health() | |
| assert health is False | |
| async def test_get_quota_status(self, mock_google_speech, provider_config): | |
| """Test quota status retrieval.""" | |
| provider = GoogleSpeechProvider(provider_config) | |
| # Set some usage | |
| provider._usage_stats["requests_this_minute"] = 10 | |
| provider._usage_stats["requests_today"] = 100 | |
| provider._usage_stats["audio_minutes_this_month"] = 15.5 | |
| quota_status = await provider.get_quota_status() | |
| assert "requests_per_minute" in quota_status | |
| assert "requests_per_day" in quota_status | |
| assert "audio_minutes_per_month" in quota_status | |
| # Check requests per minute | |
| rpm_status = quota_status["requests_per_minute"] | |
| assert rpm_status.provider == provider.name | |
| assert rpm_status.quota_type == QuotaType.REQUESTS_PER_MINUTE | |
| assert rpm_status.current_usage == 10 | |
| assert rpm_status.limit == 1000 | |
| # Check audio minutes per month | |
| ampm_status = quota_status["audio_minutes_per_month"] | |
| assert ampm_status.current_usage == 15.5 | |
| assert ampm_status.limit == 60.0 | |
| assert abs(ampm_status.percentage_used - (15.5 / 60.0)) < 0.001 | |
| async def test_transcribe_audio_unsupported_format(self, mock_google_speech, provider_config, sample_audio_data): | |
| """Test transcription with unsupported format.""" | |
| provider = GoogleSpeechProvider(provider_config) | |
| with pytest.raises(UnsupportedFormatError): | |
| await provider.transcribe_audio(sample_audio_data, "aac") | |
| async def test_transcribe_audio_unsupported_language(self, mock_google_speech, provider_config, sample_audio_data): | |
| """Test transcription with unsupported language.""" | |
| provider = GoogleSpeechProvider(provider_config) | |
| with pytest.raises(UnsupportedLanguageError): | |
| await provider.transcribe_audio(sample_audio_data, "wav", "xx-XX") | |
| async def test_transcribe_audio_quota_exceeded(self, mock_google_speech, provider_config, sample_audio_data): | |
| """Test transcription when quota is exceeded.""" | |
| provider = GoogleSpeechProvider(provider_config) | |
| # Set usage to exceed monthly limit | |
| provider._usage_stats["audio_minutes_this_month"] = 59.5 # Close to 60 minute limit | |
| with pytest.raises(QuotaExceededError): | |
| await provider.transcribe_audio(sample_audio_data, "wav", audio_duration=120) # 2 minutes | |
| async def test_transcribe_audio_rate_limit_exceeded(self, mock_google_speech, provider_config, sample_audio_data): | |
| """Test transcription when rate limit is exceeded.""" | |
| provider = GoogleSpeechProvider(provider_config) | |
| # Set usage to exceed per-minute limit | |
| provider._usage_stats["requests_this_minute"] = 1000 | |
| with pytest.raises(RateLimitExceededError): | |
| await provider.transcribe_audio(sample_audio_data, "wav") | |
| async def test_transcribe_audio_success(self, mock_google_speech, provider_config, sample_audio_data): | |
| """Test successful audio transcription.""" | |
| provider = GoogleSpeechProvider(provider_config) | |
| # Mock successful recognition response | |
| mock_alternative = Mock() | |
| mock_alternative.transcript = "Hello world" | |
| mock_alternative.confidence = 0.95 | |
| mock_alternative.words = [] | |
| mock_result = Mock() | |
| mock_result.alternatives = [mock_alternative] | |
| mock_response = Mock() | |
| mock_response.results = [mock_result] | |
| mock_google_speech['client'].recognize.return_value = mock_response | |
| result = await provider.transcribe_audio(sample_audio_data, "wav", "en-US") | |
| assert isinstance(result, TranscriptionResult) | |
| assert result.text == "Hello world" | |
| assert result.confidence == 0.95 | |
| assert result.provider == provider.name | |
| assert result.language == "en-US" | |
| assert result.is_final is True | |
| async def test_transcribe_audio_with_word_timestamps(self, mock_google_speech, provider_config, sample_audio_data): | |
| """Test transcription with word timestamps.""" | |
| provider = GoogleSpeechProvider(provider_config) | |
| # Mock word info | |
| mock_word1 = Mock() | |
| mock_word1.word = "Hello" | |
| mock_word1.start_time = Mock() | |
| mock_word1.start_time.total_seconds.return_value = 0.0 | |
| mock_word1.end_time = Mock() | |
| mock_word1.end_time.total_seconds.return_value = 0.5 | |
| mock_word1.confidence = 0.98 | |
| mock_word2 = Mock() | |
| mock_word2.word = "world" | |
| mock_word2.start_time = Mock() | |
| mock_word2.start_time.total_seconds.return_value = 0.6 | |
| mock_word2.end_time = Mock() | |
| mock_word2.end_time.total_seconds.return_value = 1.0 | |
| mock_word2.confidence = 0.92 | |
| mock_alternative = Mock() | |
| mock_alternative.transcript = "Hello world" | |
| mock_alternative.confidence = 0.95 | |
| mock_alternative.words = [mock_word1, mock_word2] | |
| mock_result = Mock() | |
| mock_result.alternatives = [mock_alternative] | |
| mock_response = Mock() | |
| mock_response.results = [mock_result] | |
| mock_google_speech['client'].recognize.return_value = mock_response | |
| result = await provider.transcribe_audio( | |
| sample_audio_data, | |
| "wav", | |
| "en-US", | |
| enable_word_time_offsets=True | |
| ) | |
| assert result.word_timestamps is not None | |
| assert len(result.word_timestamps) == 2 | |
| word1 = result.word_timestamps[0] | |
| assert word1.word == "Hello" | |
| assert word1.start_time == 0.0 | |
| assert word1.end_time == 0.5 | |
| assert word1.confidence == 0.98 | |
| word2 = result.word_timestamps[1] | |
| assert word2.word == "world" | |
| assert word2.start_time == 0.6 | |
| assert word2.end_time == 1.0 | |
| assert word2.confidence == 0.92 | |
| async def test_transcribe_audio_empty_response(self, mock_google_speech, provider_config, sample_audio_data): | |
| """Test transcription with empty response.""" | |
| provider = GoogleSpeechProvider(provider_config) | |
| # Mock empty response | |
| mock_response = Mock() | |
| mock_response.results = [] | |
| mock_google_speech['client'].recognize.return_value = mock_response | |
| result = await provider.transcribe_audio(sample_audio_data, "wav", "en-US") | |
| assert result.text == "" | |
| assert result.confidence == 0.0 | |
| assert result.provider == provider.name | |
| async def test_transcribe_audio_google_api_error(self, mock_google_speech, provider_config, sample_audio_data): | |
| """Test transcription with Google API error.""" | |
| provider = GoogleSpeechProvider(provider_config) | |
| # Mock Google API error | |
| mock_error = Mock() | |
| mock_error.code = 401 | |
| mock_google_speech['client'].recognize.side_effect = mock_error | |
| with pytest.raises(ProviderAuthenticationError): | |
| await provider.transcribe_audio(sample_audio_data, "wav", "en-US") | |
| async def test_transcribe_streaming_unsupported_format(self, mock_google_speech, provider_config): | |
| """Test streaming transcription with unsupported format.""" | |
| provider = GoogleSpeechProvider(provider_config) | |
| async def mock_audio_stream(): | |
| yield b'audio_chunk' | |
| with pytest.raises(UnsupportedFormatError): | |
| async for _ in provider.transcribe_streaming(mock_audio_stream(), "aac"): | |
| pass | |
| async def test_transcribe_streaming_success(self, mock_google_speech, provider_config): | |
| """Test successful streaming transcription.""" | |
| provider = GoogleSpeechProvider(provider_config) | |
| # Mock streaming response | |
| mock_alternative = Mock() | |
| mock_alternative.transcript = "Streaming text" | |
| mock_alternative.confidence = 0.85 | |
| mock_result = Mock() | |
| mock_result.alternatives = [mock_alternative] | |
| mock_result.is_final = True | |
| mock_response = Mock() | |
| mock_response.results = [mock_result] | |
| mock_google_speech['client'].streaming_recognize.return_value = [mock_response] | |
| async def mock_audio_stream(): | |
| yield b'audio_chunk_1' | |
| yield b'audio_chunk_2' | |
| results = [] | |
| async for result in provider.transcribe_streaming(mock_audio_stream(), "wav", "en-US"): | |
| results.append(result) | |
| assert len(results) == 1 | |
| assert results[0].text == "Streaming text" | |
| assert results[0].confidence == 0.85 | |
| assert results[0].is_final is True | |
| async def test_usage_stats_reset(self, mock_google_speech, provider_config): | |
| """Test usage statistics reset functionality.""" | |
| provider = GoogleSpeechProvider(provider_config) | |
| # Set usage stats to old values | |
| old_time = datetime.now(timezone.utc) - timedelta(days=2) | |
| provider._usage_stats["last_daily_reset"] = old_time.date() | |
| provider._usage_stats["requests_today"] = 100 | |
| # Trigger reset by calling _reset_counters_if_needed | |
| await provider._reset_counters_if_needed() | |
| # Check that daily counter was reset | |
| assert provider._usage_stats["requests_today"] == 0 | |
| assert provider._usage_stats["last_daily_reset"] == datetime.now(timezone.utc).date() | |
| def test_create_google_speech_provider_factory(self, mock_google_speech): | |
| """Test the factory function for creating GoogleSpeechProvider.""" | |
| provider = create_google_speech_provider( | |
| name="custom_google", | |
| priority=5, | |
| api_credentials={"service_account_key": "test_key"} | |
| ) | |
| assert provider.name == "custom_google" | |
| assert provider.config.priority == 5 | |
| assert provider.config.api_credentials["service_account_key"] == "test_key" | |
| assert provider.config.provider_type == ProviderType.GOOGLE_SPEECH | |
| class TestGoogleSpeechProviderIntegration: | |
| """Integration tests for GoogleSpeechProvider.""" | |
| def mock_google_speech_integration(self): | |
| """Mock Google Cloud Speech modules for integration tests.""" | |
| with patch('voice_control.providers.google_speech_provider.GOOGLE_SPEECH_AVAILABLE', True): | |
| with patch('voice_control.providers.google_speech_provider.speech') as mock_speech: | |
| with patch('voice_control.providers.google_speech_provider.service_account') as mock_sa: | |
| with patch('voice_control.providers.google_speech_provider.google_exceptions') as mock_exc: | |
| # Setup mock speech client | |
| mock_client = Mock() | |
| mock_speech.SpeechClient.return_value = mock_client | |
| # Setup mock recognition config | |
| mock_config = Mock() | |
| mock_speech.RecognitionConfig.return_value = mock_config | |
| mock_speech.RecognitionConfig.AudioEncoding = Mock() | |
| mock_speech.RecognitionConfig.AudioEncoding.LINEAR16 = "LINEAR16" | |
| # Setup mock audio | |
| mock_audio = Mock() | |
| mock_speech.RecognitionAudio.return_value = mock_audio | |
| yield { | |
| 'speech': mock_speech, | |
| 'service_account': mock_sa, | |
| 'exceptions': mock_exc, | |
| 'client': mock_client | |
| } | |
| async def test_full_transcription_workflow(self, mock_google_speech_integration): | |
| """Test complete transcription workflow.""" | |
| # Create provider with realistic config | |
| config = ProviderConfig( | |
| name="integration_test", | |
| provider_type=ProviderType.GOOGLE_SPEECH, | |
| enabled=True, | |
| priority=2, | |
| free_tier_limits={ | |
| "audio_minutes_per_month": 60.0, | |
| "requests_per_minute": 1000, | |
| "requests_per_day": 50000 | |
| }, | |
| rate_limits={ | |
| "requests_per_minute": 1000, | |
| "requests_per_day": 50000 | |
| }, | |
| supported_formats=["wav", "mp3", "flac"], | |
| supported_languages=["en-US", "es-ES"], | |
| cost_per_minute=0.006, | |
| api_credentials={ | |
| "service_account_key": '{"type": "service_account", "project_id": "test"}' | |
| } | |
| ) | |
| provider = GoogleSpeechProvider(config) | |
| # Mock successful transcription | |
| mock_alternative = Mock() | |
| mock_alternative.transcript = "Integration test successful" | |
| mock_alternative.confidence = 0.92 | |
| mock_alternative.words = [] | |
| mock_result = Mock() | |
| mock_result.alternatives = [mock_alternative] | |
| mock_response = Mock() | |
| mock_response.results = [mock_result] | |
| mock_google_speech['client'].recognize.return_value = mock_response | |
| # Test transcription | |
| audio_data = b'\x00\x01' * 4000 # 8KB sample | |
| result = await provider.transcribe_audio(audio_data, "wav", "en-US") | |
| # Verify result | |
| assert result.text == "Integration test successful" | |
| assert result.confidence == 0.92 | |
| assert result.provider == "integration_test" | |
| assert result.language == "en-US" | |
| # Check that usage was tracked | |
| quota_status = await provider.get_quota_status() | |
| assert quota_status["requests_per_minute"].current_usage == 1 | |
| assert quota_status["audio_minutes_per_month"].current_usage > 0 | |
| async def test_quota_management_workflow(self, mock_google_speech): | |
| """Test quota management across multiple requests.""" | |
| provider = create_google_speech_provider( | |
| api_credentials={"service_account_key": "test"} | |
| ) | |
| # Mock successful responses | |
| mock_alternative = Mock() | |
| mock_alternative.transcript = "Test" | |
| mock_alternative.confidence = 0.9 | |
| mock_alternative.words = [] | |
| mock_result = Mock() | |
| mock_result.alternatives = [mock_alternative] | |
| mock_response = Mock() | |
| mock_response.results = [mock_result] | |
| mock_google_speech['client'].recognize.return_value = mock_response | |
| # Make multiple requests | |
| audio_data = b'\x00\x01' * 1000 | |
| for i in range(5): | |
| result = await provider.transcribe_audio(audio_data, "wav", "en-US") | |
| assert result.text == "Test" | |
| # Check quota tracking | |
| quota_status = await provider.get_quota_status() | |
| assert quota_status["requests_per_minute"].current_usage == 5 | |
| # Verify cost estimation | |
| cost = await provider.estimate_cost(300) # 5 minutes | |
| assert cost == 0.0 # Should be free within tier |