stemsplit-backend / voice_control /tests /test_web_speech_integration.py
nifty-coder
Voice control
8cbe6eb
Raw History Blame Contribute Delete
14.4 kB
"""
Integration tests for WebSpeechProvider with the voice control system.
This module tests the integration of WebSpeechProvider with other components
like ProviderManager, RateLimiter, and CacheManager.
"""
import pytest
import asyncio
from unittest.mock import AsyncMock, MagicMock, patch
from voice_control.providers.web_speech_provider import create_web_speech_provider
from voice_control.provider_manager import ProviderManager
from voice_control.rate_limiter import RateLimiter
from voice_control.cache_manager import CacheManager
from voice_control.models import ProviderConfig, ProviderType, TranscriptionResult
from voice_control.exceptions import ProviderUnavailableError, QuotaExceededError
class TestWebSpeechProviderIntegration:
"""Integration tests for WebSpeechProvider."""
@pytest.fixture
def web_speech_provider(self):
"""Create a WebSpeechProvider for testing."""
return create_web_speech_provider(
name="test_web_speech",
priority=1
)
@pytest.fixture
def provider_manager(self):
"""Create a ProviderManager for testing."""
return ProviderManager()
@pytest.fixture
def sample_audio_data(self):
"""Create sample audio data for testing."""
return b'\x00' * (16000 * 2) # 1 second of 16kHz, 16-bit audio
@pytest.mark.asyncio
async def test_provider_registration_with_manager(self, provider_manager, web_speech_provider):
"""Test registering WebSpeechProvider with ProviderManager."""
# Register the provider
await provider_manager.register_provider(web_speech_provider)
# Check that provider is registered
status = await provider_manager.get_provider_status()
assert "test_web_speech" in status
provider_status = status["test_web_speech"]
assert provider_status.name == "test_web_speech"
assert provider_status.available is True
@pytest.mark.asyncio
async def test_transcription_through_manager(self, provider_manager, web_speech_provider, sample_audio_data):
"""Test transcription through ProviderManager using WebSpeechProvider."""
# Mock browser compatibility
with patch.object(web_speech_provider, '_check_browser_compatibility'):
web_speech_provider._browser_compatible = True
# Register provider
await provider_manager.register_provider(web_speech_provider)
# Perform transcription through manager
result = await provider_manager.transcribe_audio(
sample_audio_data,
"webm",
"en-US"
)
# Verify result
assert isinstance(result, TranscriptionResult)
assert result.provider == "test_web_speech"
assert result.text is not None
assert result.confidence > 0
@pytest.mark.asyncio
async def test_provider_health_monitoring(self, provider_manager, web_speech_provider):
"""Test health monitoring of WebSpeechProvider."""
# Mock browser compatibility check
with patch.object(web_speech_provider, '_check_browser_compatibility') as mock_check:
mock_check.return_value = None
web_speech_provider._browser_compatible = True
# Register provider
await provider_manager.register_provider(web_speech_provider)
# Check health through manager
status = await provider_manager.get_provider_status()
provider_status = status["test_web_speech"]
assert provider_status.available is True
assert provider_status.response_time_avg >= 0
@pytest.mark.asyncio
async def test_provider_fallback_behavior(self, provider_manager, sample_audio_data):
"""Test fallback behavior when WebSpeechProvider fails."""
# Create two providers with different priorities
primary_provider = create_web_speech_provider(
name="primary_web_speech",
priority=1
)
fallback_provider = create_web_speech_provider(
name="fallback_web_speech",
priority=2
)
# Mock primary provider to fail
with patch.object(primary_provider, 'transcribe_audio') as mock_primary, \
patch.object(fallback_provider, 'transcribe_audio') as mock_fallback, \
patch.object(primary_provider, '_check_browser_compatibility'), \
patch.object(fallback_provider, '_check_browser_compatibility'):
# Set up browser compatibility
primary_provider._browser_compatible = True
fallback_provider._browser_compatible = True
# Primary fails, fallback succeeds
mock_primary.side_effect = ProviderUnavailableError(
"primary_web_speech",
"Browser not supported"
)
mock_fallback.return_value = TranscriptionResult(
text="Fallback transcription",
confidence=0.8,
provider="fallback_web_speech",
processing_time=0.1,
audio_duration=1.0,
language="en-US"
)
# Register both providers
await provider_manager.register_provider(primary_provider)
await provider_manager.register_provider(fallback_provider)
# Perform transcription - should use fallback
result = await provider_manager.transcribe_audio(
sample_audio_data,
"webm",
"en-US"
)
# Verify fallback was used
assert result.provider == "fallback_web_speech"
assert result.text == "Fallback transcription"
@pytest.mark.asyncio
async def test_streaming_through_manager(self, provider_manager, web_speech_provider):
"""Test streaming transcription through ProviderManager."""
async def mock_audio_stream():
"""Mock audio stream."""
for i in range(3):
yield b'\x00' * 8000 # 0.5 seconds each
with patch.object(web_speech_provider, '_check_browser_compatibility'):
web_speech_provider._browser_compatible = True
# Register provider
await provider_manager.register_provider(web_speech_provider)
# Perform streaming transcription
results = []
async for result in provider_manager.transcribe_streaming(
mock_audio_stream(),
"webm",
"en-US"
):
results.append(result)
# Verify results
assert len(results) > 0
assert all(r.provider == "test_web_speech" for r in results)
@pytest.mark.asyncio
async def test_quota_management_integration(self, web_speech_provider, sample_audio_data):
"""Test quota management with WebSpeechProvider."""
# Set very low quota limits
web_speech_provider.config.free_tier_limits = {
"max_daily_requests": 1,
"max_daily_minutes": 0.1
}
with patch.object(web_speech_provider, '_check_browser_compatibility'):
web_speech_provider._browser_compatible = True
# First transcription should succeed
result1 = await web_speech_provider.transcribe_audio(
sample_audio_data,
"webm",
"en-US",
audio_duration=0.05 # 0.05 seconds
)
assert result1 is not None
# Second transcription should fail due to quota
with pytest.raises(QuotaExceededError):
await web_speech_provider.transcribe_audio(
sample_audio_data,
"webm",
"en-US",
audio_duration=0.05
)
@pytest.mark.asyncio
async def test_format_and_language_validation(self, provider_manager, web_speech_provider, sample_audio_data):
"""Test format and language validation through manager."""
with patch.object(web_speech_provider, '_check_browser_compatibility'):
web_speech_provider._browser_compatible = True
# Register provider
await provider_manager.register_provider(web_speech_provider)
# Test unsupported format
with pytest.raises(Exception): # Should raise UnsupportedFormatError or similar
await provider_manager.transcribe_audio(
sample_audio_data,
"unsupported_format",
"en-US"
)
# Test unsupported language
with pytest.raises(Exception): # Should raise UnsupportedLanguageError or similar
await provider_manager.transcribe_audio(
sample_audio_data,
"webm",
"unsupported-LANG"
)
@pytest.mark.asyncio
async def test_provider_metrics_collection(self, provider_manager, web_speech_provider, sample_audio_data):
"""Test that provider metrics are collected correctly."""
with patch.object(web_speech_provider, '_check_browser_compatibility'):
web_speech_provider._browser_compatible = True
# Register provider
await provider_manager.register_provider(web_speech_provider)
# Perform several transcriptions
for i in range(3):
await provider_manager.transcribe_audio(
sample_audio_data,
"webm",
"en-US"
)
# Check that usage stats were updated
quota_status = await web_speech_provider.get_quota_status()
requests_quota = quota_status["requests_per_day"]
audio_quota = quota_status["audio_minutes_per_day"]
assert requests_quota.current_usage == 3
# Audio usage should be greater than 0 since we processed audio
assert audio_quota.current_usage >= 0 # Changed from > 0 to >= 0 since it might be very small
@pytest.mark.asyncio
async def test_concurrent_transcriptions(self, provider_manager, web_speech_provider, sample_audio_data):
"""Test concurrent transcriptions with WebSpeechProvider."""
with patch.object(web_speech_provider, '_check_browser_compatibility'):
web_speech_provider._browser_compatible = True
# Register provider
await provider_manager.register_provider(web_speech_provider)
# Perform concurrent transcriptions
tasks = []
for i in range(5):
task = provider_manager.transcribe_audio(
sample_audio_data,
"webm",
"en-US"
)
tasks.append(task)
# Wait for all to complete
results = await asyncio.gather(*tasks)
# Verify all succeeded
assert len(results) == 5
assert all(isinstance(r, TranscriptionResult) for r in results)
assert all(r.provider == "test_web_speech" for r in results)
class TestWebSpeechProviderSystemIntegration:
"""System-level integration tests."""
@pytest.mark.asyncio
async def test_complete_voice_control_workflow(self):
"""Test complete workflow with WebSpeechProvider as primary provider."""
# Create a complete system setup
provider_manager = ProviderManager()
web_speech_provider = create_web_speech_provider(
name="system_web_speech",
priority=1 # Highest priority
)
sample_audio = b'\x00' * (16000 * 2) # 1 second
with patch.object(web_speech_provider, '_check_browser_compatibility'):
web_speech_provider._browser_compatible = True
# Register provider
await provider_manager.register_provider(web_speech_provider)
# 1. Check system health
status = await provider_manager.get_provider_status()
assert "system_web_speech" in status
assert status["system_web_speech"].available is True
# 2. Perform transcription
result = await provider_manager.transcribe_audio(
sample_audio,
"webm",
"en-US"
)
# 3. Verify result quality
assert result.provider == "system_web_speech"
assert result.confidence > 0
assert result.processing_time > 0
assert result.audio_duration > 0
# 4. Check quota usage
quota_status = await web_speech_provider.get_quota_status()
assert quota_status["requests_per_day"].current_usage == 1
# 5. Test streaming capability
async def audio_stream():
for _ in range(2):
yield b'\x00' * 8000
streaming_results = []
async for stream_result in provider_manager.transcribe_streaming(
audio_stream(),
"webm",
"en-US"
):
streaming_results.append(stream_result)
assert len(streaming_results) > 0
assert all(r.provider == "system_web_speech" for r in streaming_results)
print("✓ Complete voice control workflow test passed")
if __name__ == "__main__":
# Run a quick integration test
async def quick_test():
test_instance = TestWebSpeechProviderSystemIntegration()
await test_instance.test_complete_voice_control_workflow()
print("Integration test completed successfully!")
asyncio.run(quick_test())