Spaces:
Runtime error
Runtime error
Download voice_control/tests/test_web_speech_provider.py from nifty-coder/stemsplit-backend: direct link, hf CLI and curl.
- Browser
- Download file 22.8 kB
-
https://huggingface.co/spaces/nifty-coder/stemsplit-backend/resolve/main/voice_control/tests/test_web_speech_provider.py
- Command line
-
hf download hf://spaces/nifty-coder/stemsplit-backend/voice_control/tests/test_web_speech_provider.py
-
curl -L -o test_web_speech_provider.py https://huggingface.co/spaces/nifty-coder/stemsplit-backend/resolve/main/voice_control/tests/test_web_speech_provider.py
22.8 kB
| """ | |
| Unit tests for WebSpeechProvider. | |
| This module contains comprehensive unit tests for the Web Speech API provider | |
| implementation, covering transcription, streaming, error handling, and browser | |
| compatibility scenarios. | |
| """ | |
| import pytest | |
| import asyncio | |
| from datetime import datetime, timezone | |
| from unittest.mock import AsyncMock, MagicMock, patch | |
| from voice_control.providers.web_speech_provider import WebSpeechProvider, create_web_speech_provider | |
| from voice_control.models import ProviderConfig, ProviderType, TranscriptionResult, QuotaStatus, QuotaType | |
| from voice_control.exceptions import ( | |
| ProviderUnavailableError, | |
| UnsupportedFormatError, | |
| UnsupportedLanguageError, | |
| QuotaExceededError, | |
| TranscriptionError | |
| ) | |
| class TestWebSpeechProvider: | |
| """Test suite for WebSpeechProvider class.""" | |
| def provider_config(self): | |
| """Create a test provider configuration.""" | |
| return ProviderConfig( | |
| name="test_web_speech", | |
| provider_type=ProviderType.WEB_SPEECH_API, | |
| enabled=True, | |
| priority=1, | |
| free_tier_limits={ | |
| "max_daily_requests": 100, | |
| "max_daily_minutes": 10.0 | |
| }, | |
| rate_limits={ | |
| "requests_per_minute": 60, | |
| "requests_per_hour": 1000 | |
| }, | |
| supported_formats=["webm", "wav", "mp3"], | |
| supported_languages=["en-US", "es-ES", "fr-FR"], | |
| cost_per_minute=0.0, | |
| api_credentials={}, | |
| timeout_seconds=30, | |
| max_retries=2 | |
| ) | |
| def provider(self, provider_config): | |
| """Create a WebSpeechProvider instance for testing.""" | |
| return WebSpeechProvider(provider_config) | |
| def sample_audio_data(self): | |
| """Create sample audio data for testing.""" | |
| # Simulate 1 second of 16kHz, 16-bit audio | |
| return b'\x00' * (16000 * 2) | |
| def test_initialization(self, provider_config): | |
| """Test provider initialization.""" | |
| provider = WebSpeechProvider(provider_config) | |
| assert provider.name == "test_web_speech" | |
| assert provider.provider_type == ProviderType.WEB_SPEECH_API | |
| assert provider._usage_stats["requests_today"] == 0 | |
| assert provider._usage_stats["audio_minutes_today"] == 0.0 | |
| assert provider._browser_compatible is None | |
| assert provider._active_sessions == {} | |
| def test_initialization_invalid_provider_type(self): | |
| """Test initialization with invalid provider type.""" | |
| config = ProviderConfig( | |
| name="invalid", | |
| provider_type=ProviderType.GOOGLE_SPEECH, # Wrong type | |
| enabled=True, | |
| priority=1, | |
| free_tier_limits={}, | |
| rate_limits={}, | |
| supported_formats=["webm"], | |
| supported_languages=["en-US"], | |
| cost_per_minute=0.0, | |
| api_credentials={} | |
| ) | |
| with pytest.raises(ValueError, match="Invalid provider type"): | |
| WebSpeechProvider(config) | |
| def test_supports_format(self, provider): | |
| """Test format support checking.""" | |
| assert provider.supports_format("webm") is True | |
| assert provider.supports_format("WEBM") is True # Case insensitive | |
| assert provider.supports_format("wav") is True | |
| assert provider.supports_format("mp3") is True | |
| assert provider.supports_format("flac") is False | |
| assert provider.supports_format("unknown") is False | |
| def test_supports_language(self, provider): | |
| """Test language support checking.""" | |
| # Test languages that are in the full SUPPORTED_LANGUAGES list | |
| assert provider.supports_language("en-US") is True | |
| assert provider.supports_language("es-ES") is True | |
| assert provider.supports_language("fr-FR") is True | |
| assert provider.supports_language("de-DE") is True # This is in the full list | |
| assert provider.supports_language("unknown-XX") is False | |
| async def test_estimate_cost(self, provider): | |
| """Test cost estimation (should always be 0.0 for Web Speech API).""" | |
| cost = await provider.estimate_cost(60.0) # 1 minute | |
| assert cost == 0.0 | |
| cost = await provider.estimate_cost(3600.0) # 1 hour | |
| assert cost == 0.0 | |
| async def test_check_health_success(self, provider): | |
| """Test successful health check.""" | |
| with patch.object(provider, '_check_browser_compatibility') as mock_check: | |
| mock_check.return_value = None | |
| provider._browser_compatible = True | |
| result = await provider.check_health() | |
| assert result is True | |
| mock_check.assert_called_once() | |
| async def test_check_health_failure(self, provider): | |
| """Test health check failure.""" | |
| with patch.object(provider, '_check_browser_compatibility') as mock_check: | |
| mock_check.side_effect = Exception("Browser not supported") | |
| result = await provider.check_health() | |
| assert result is False | |
| async def test_get_quota_status(self, provider): | |
| """Test quota status retrieval.""" | |
| # Set some usage | |
| provider._usage_stats["requests_today"] = 10 | |
| provider._usage_stats["audio_minutes_today"] = 5.0 | |
| quota_status = await provider.get_quota_status() | |
| assert "requests_per_day" in quota_status | |
| assert "audio_minutes_per_day" in quota_status | |
| requests_quota = quota_status["requests_per_day"] | |
| assert requests_quota.provider == provider.name | |
| assert requests_quota.quota_type == QuotaType.REQUESTS_PER_DAY | |
| assert requests_quota.current_usage == 10 | |
| assert requests_quota.limit == float('inf') | |
| audio_quota = quota_status["audio_minutes_per_day"] | |
| assert audio_quota.provider == provider.name | |
| assert audio_quota.quota_type == QuotaType.AUDIO_MINUTES_PER_DAY | |
| assert audio_quota.current_usage == 5.0 | |
| assert audio_quota.limit == float('inf') | |
| async def test_transcribe_audio_success(self, provider, sample_audio_data): | |
| """Test successful audio transcription.""" | |
| with patch.object(provider, '_check_browser_compatibility') as mock_check, \ | |
| patch.object(provider, '_check_usage_quota') as mock_quota, \ | |
| patch.object(provider, '_perform_transcription') as mock_transcribe, \ | |
| patch.object(provider, '_update_usage_stats') as mock_update: | |
| mock_check.return_value = None | |
| mock_quota.return_value = None | |
| mock_update.return_value = None | |
| expected_result = TranscriptionResult( | |
| text="Test transcription", | |
| confidence=0.85, | |
| provider=provider.name, | |
| processing_time=0.1, | |
| audio_duration=1.0, | |
| language="en-US" | |
| ) | |
| mock_transcribe.return_value = expected_result | |
| result = await provider.transcribe_audio( | |
| sample_audio_data, | |
| "webm", | |
| "en-US", | |
| audio_duration=1.0 | |
| ) | |
| assert result == expected_result | |
| mock_check.assert_called_once() | |
| mock_quota.assert_called_once_with(1.0) | |
| mock_transcribe.assert_called_once() | |
| mock_update.assert_called_once() | |
| async def test_transcribe_audio_unsupported_format(self, provider, sample_audio_data): | |
| """Test transcription with unsupported format.""" | |
| with patch.object(provider, '_check_browser_compatibility'): | |
| with pytest.raises(UnsupportedFormatError) as exc_info: | |
| await provider.transcribe_audio(sample_audio_data, "flac", "en-US") | |
| assert exc_info.value.provider == provider.name | |
| assert exc_info.value.format == "flac" | |
| async def test_transcribe_audio_unsupported_language(self, provider, sample_audio_data): | |
| """Test transcription with unsupported language.""" | |
| with patch.object(provider, '_check_browser_compatibility'): | |
| with pytest.raises(UnsupportedLanguageError) as exc_info: | |
| await provider.transcribe_audio(sample_audio_data, "webm", "unknown-XX") | |
| assert exc_info.value.provider == provider.name | |
| assert exc_info.value.language == "unknown-XX" | |
| async def test_transcribe_audio_browser_unavailable(self, provider, sample_audio_data): | |
| """Test transcription when browser is unavailable.""" | |
| with patch.object(provider, '_check_browser_compatibility') as mock_check: | |
| mock_check.side_effect = ProviderUnavailableError( | |
| provider.name, | |
| "Browser does not support Web Speech API" | |
| ) | |
| with pytest.raises(ProviderUnavailableError): | |
| await provider.transcribe_audio(sample_audio_data, "webm", "en-US") | |
| async def test_transcribe_audio_quota_exceeded(self, provider, sample_audio_data): | |
| """Test transcription when quota is exceeded.""" | |
| with patch.object(provider, '_check_browser_compatibility'), \ | |
| patch.object(provider, '_check_usage_quota') as mock_quota: | |
| mock_quota.side_effect = QuotaExceededError( | |
| provider.name, | |
| "requests_per_day", | |
| 100, | |
| 100 | |
| ) | |
| with pytest.raises(QuotaExceededError): | |
| await provider.transcribe_audio(sample_audio_data, "webm", "en-US") | |
| async def test_transcribe_streaming_success(self, provider): | |
| """Test successful streaming transcription.""" | |
| async def mock_audio_stream(): | |
| """Mock audio stream generator.""" | |
| for i in range(3): | |
| yield b'\x00' * 8000 # 0.5 seconds of audio each | |
| with patch.object(provider, '_check_browser_compatibility'), \ | |
| patch.object(provider, '_check_usage_quota'), \ | |
| patch.object(provider, '_process_streaming_chunk') as mock_process, \ | |
| patch.object(provider, '_update_usage_stats'): | |
| # Mock streaming results | |
| mock_results = [ | |
| TranscriptionResult( | |
| text=f"Chunk {i}", | |
| confidence=0.8, | |
| provider=provider.name, | |
| processing_time=0.05, | |
| audio_duration=0.5, | |
| language="en-US", | |
| is_final=i == 2 | |
| ) | |
| for i in range(3) | |
| ] | |
| mock_process.side_effect = mock_results | |
| results = [] | |
| async for result in provider.transcribe_streaming( | |
| mock_audio_stream(), | |
| "webm", | |
| "en-US" | |
| ): | |
| results.append(result) | |
| assert len(results) == 3 | |
| assert all(r.provider == provider.name for r in results) | |
| assert results[-1].is_final is True | |
| async def test_transcribe_streaming_with_errors(self, provider): | |
| """Test streaming transcription with chunk processing errors.""" | |
| async def mock_audio_stream(): | |
| """Mock audio stream generator.""" | |
| for i in range(3): | |
| yield b'\x00' * 8000 | |
| with patch.object(provider, '_check_browser_compatibility'), \ | |
| patch.object(provider, '_check_usage_quota'), \ | |
| patch.object(provider, '_process_streaming_chunk') as mock_process, \ | |
| patch.object(provider, '_update_usage_stats'): | |
| # First chunk succeeds, second fails, third succeeds | |
| mock_process.side_effect = [ | |
| TranscriptionResult( | |
| text="Chunk 0", | |
| confidence=0.8, | |
| provider=provider.name, | |
| processing_time=0.05, | |
| audio_duration=0.5, | |
| language="en-US" | |
| ), | |
| Exception("Processing error"), | |
| TranscriptionResult( | |
| text="Chunk 2", | |
| confidence=0.8, | |
| provider=provider.name, | |
| processing_time=0.05, | |
| audio_duration=0.5, | |
| language="en-US" | |
| ) | |
| ] | |
| results = [] | |
| async for result in provider.transcribe_streaming( | |
| mock_audio_stream(), | |
| "webm", | |
| "en-US" | |
| ): | |
| results.append(result) | |
| # Should get 2 results (error chunk is skipped) | |
| assert len(results) == 2 | |
| assert results[0].text == "Chunk 0" | |
| assert results[1].text == "Chunk 2" | |
| async def test_check_browser_compatibility_cached(self, provider): | |
| """Test browser compatibility check with caching.""" | |
| provider._browser_compatible = True | |
| provider._last_compatibility_check = datetime.now(timezone.utc) | |
| # Should not raise exception due to caching | |
| await provider._check_browser_compatibility() | |
| # Set incompatible and test exception | |
| provider._browser_compatible = False | |
| with pytest.raises(ProviderUnavailableError): | |
| await provider._check_browser_compatibility() | |
| async def test_check_usage_quota_success(self, provider): | |
| """Test successful usage quota check.""" | |
| provider._usage_stats["requests_today"] = 50 | |
| provider._usage_stats["audio_minutes_today"] = 5.0 | |
| # Should not raise exception | |
| await provider._check_usage_quota(60.0) # 1 minute | |
| async def test_check_usage_quota_requests_exceeded(self, provider): | |
| """Test usage quota check when requests are exceeded.""" | |
| provider.config.free_tier_limits["max_daily_requests"] = 100 | |
| provider._usage_stats["requests_today"] = 100 | |
| with pytest.raises(QuotaExceededError) as exc_info: | |
| await provider._check_usage_quota(60.0) | |
| assert exc_info.value.quota_type == "requests_per_day" | |
| assert exc_info.value.current_usage == 100 | |
| assert exc_info.value.limit == 100 | |
| async def test_check_usage_quota_minutes_exceeded(self, provider): | |
| """Test usage quota check when audio minutes are exceeded.""" | |
| provider.config.free_tier_limits["max_daily_minutes"] = 10.0 | |
| provider._usage_stats["audio_minutes_today"] = 9.5 | |
| with pytest.raises(QuotaExceededError) as exc_info: | |
| await provider._check_usage_quota(60.0) # 1 minute would exceed | |
| assert exc_info.value.quota_type == "audio_minutes_per_day" | |
| async def test_perform_transcription(self, provider, sample_audio_data): | |
| """Test the transcription performance simulation.""" | |
| params = { | |
| "language": "en-US", | |
| "session_id": "test_session", | |
| "continuous": False, | |
| "interim_results": True | |
| } | |
| result = await provider._perform_transcription( | |
| sample_audio_data, | |
| "webm", | |
| params, | |
| 30.0 | |
| ) | |
| assert isinstance(result, TranscriptionResult) | |
| assert result.provider == provider.name | |
| assert result.language == "en-US" | |
| assert result.session_id == "test_session" | |
| assert result.confidence > 0 | |
| assert result.processing_time > 0 | |
| assert result.is_final is True | |
| async def test_process_streaming_chunk_small_chunk(self, provider): | |
| """Test processing of small streaming chunks (should return None).""" | |
| small_chunk = b'\x00' * 500 # Very small chunk | |
| result = await provider._process_streaming_chunk( | |
| small_chunk, | |
| "session_123", | |
| "en-US", | |
| "webm" | |
| ) | |
| assert result is None | |
| async def test_process_streaming_chunk_large_chunk(self, provider): | |
| """Test processing of large streaming chunks.""" | |
| large_chunk = b'\x00' * 10000 # Large chunk | |
| result = await provider._process_streaming_chunk( | |
| large_chunk, | |
| "session_123", | |
| "en-US", | |
| "webm", | |
| interim_results=True | |
| ) | |
| assert result is not None | |
| assert isinstance(result, TranscriptionResult) | |
| assert result.session_id == "session_123" | |
| assert result.language == "en-US" | |
| assert result.is_final is True # Large chunks are marked as final | |
| async def test_update_usage_stats(self, provider): | |
| """Test usage statistics updates.""" | |
| initial_requests = provider._usage_stats["requests_today"] | |
| initial_minutes = provider._usage_stats["audio_minutes_today"] | |
| await provider._update_usage_stats(120.0, 0.5) # 2 minutes, 0.5s processing | |
| assert provider._usage_stats["requests_today"] == initial_requests + 1 | |
| assert provider._usage_stats["audio_minutes_today"] == initial_minutes + 2.0 | |
| async def test_reset_daily_stats_if_needed(self, provider): | |
| """Test daily statistics reset.""" | |
| # Set some usage | |
| provider._usage_stats["requests_today"] = 50 | |
| provider._usage_stats["audio_minutes_today"] = 10.0 | |
| # Simulate next day | |
| from datetime import date, timedelta | |
| yesterday = date.today() - timedelta(days=1) | |
| provider._usage_stats["last_reset"] = yesterday | |
| await provider._reset_daily_stats_if_needed() | |
| assert provider._usage_stats["requests_today"] == 0 | |
| assert provider._usage_stats["audio_minutes_today"] == 0.0 | |
| # The reset should update to current date | |
| assert provider._usage_stats["last_reset"] >= yesterday | |
| class TestWebSpeechProviderFactory: | |
| """Test suite for WebSpeechProvider factory function.""" | |
| def test_create_web_speech_provider_defaults(self): | |
| """Test factory function with default parameters.""" | |
| provider = create_web_speech_provider() | |
| assert provider.name == "web_speech_api" | |
| assert provider.config.priority == 1 | |
| assert provider.config.provider_type == ProviderType.WEB_SPEECH_API | |
| assert provider.config.enabled is True | |
| assert provider.config.cost_per_minute == 0.0 | |
| def test_create_web_speech_provider_custom(self): | |
| """Test factory function with custom parameters.""" | |
| provider = create_web_speech_provider( | |
| name="custom_web_speech", | |
| priority=5, | |
| enabled=False, | |
| timeout_seconds=60 | |
| ) | |
| assert provider.name == "custom_web_speech" | |
| assert provider.config.priority == 5 | |
| assert provider.config.enabled is False | |
| assert provider.config.timeout_seconds == 60 | |
| def test_create_web_speech_provider_overrides(self): | |
| """Test factory function with configuration overrides.""" | |
| provider = create_web_speech_provider( | |
| free_tier_limits={ | |
| "max_daily_requests": 500, | |
| "max_daily_minutes": 30.0 | |
| }, | |
| rate_limits={ | |
| "requests_per_minute": 120 | |
| } | |
| ) | |
| assert provider.config.free_tier_limits["max_daily_requests"] == 500 | |
| assert provider.config.free_tier_limits["max_daily_minutes"] == 30.0 | |
| assert provider.config.rate_limits["requests_per_minute"] == 120 | |
| # Integration test scenarios | |
| class TestWebSpeechProviderIntegration: | |
| """Integration tests for WebSpeechProvider.""" | |
| async def test_full_transcription_workflow(self): | |
| """Test complete transcription workflow.""" | |
| provider = create_web_speech_provider() | |
| sample_audio = b'\x00' * (16000 * 2) # 1 second of audio | |
| # Mock browser compatibility | |
| with patch.object(provider, '_check_browser_compatibility'): | |
| provider._browser_compatible = True | |
| # Perform transcription | |
| result = await provider.transcribe_audio( | |
| sample_audio, | |
| "webm", | |
| "en-US", | |
| audio_duration=1.0 | |
| ) | |
| # Verify result | |
| assert isinstance(result, TranscriptionResult) | |
| assert result.provider == provider.name | |
| assert result.audio_duration > 0 | |
| assert result.processing_time > 0 | |
| assert result.confidence > 0 | |
| # Check usage stats were updated | |
| assert provider._usage_stats["requests_today"] == 1 | |
| assert provider._usage_stats["audio_minutes_today"] > 0 | |
| async def test_streaming_workflow_with_session_management(self): | |
| """Test streaming workflow with session management.""" | |
| provider = create_web_speech_provider() | |
| async def audio_stream(): | |
| for i in range(5): | |
| yield b'\x00' * 8000 # 0.5 seconds each | |
| with patch.object(provider, '_check_browser_compatibility'): | |
| provider._browser_compatible = True | |
| session_id = None | |
| results = [] | |
| async for result in provider.transcribe_streaming( | |
| audio_stream(), | |
| "webm", | |
| "en-US" | |
| ): | |
| results.append(result) | |
| if session_id is None: | |
| session_id = result.session_id | |
| else: | |
| assert result.session_id == session_id | |
| # Verify session was cleaned up | |
| assert session_id not in provider._active_sessions | |
| # Verify we got some results | |
| assert len(results) > 0 | |
| assert all(r.provider == provider.name for r in results) |