stemsplit-backend / voice_control /tests /test_azure_speech_integration.py
nifty-coder
Voice control
8cbe6eb
Raw History Blame Contribute Delete
23.1 kB
"""
Integration tests for Azure Speech Services provider.
This module contains integration tests that verify the AzureSpeechProvider
works correctly with the broader voice control system, including provider
manager integration, error handling, and real-world scenarios.
"""
import pytest
import asyncio
import json
from unittest.mock import Mock, AsyncMock, patch, MagicMock
from datetime import datetime, timezone, timedelta
from typing import Dict, Any, List
from voice_control.providers.azure_speech_provider import AzureSpeechProvider, create_azure_speech_provider
from voice_control.models import (
ProviderConfig,
TranscriptionResult,
QuotaStatus,
QuotaType,
ProviderType,
ProviderStatus
)
from voice_control.exceptions import (
ProviderError,
ProviderUnavailableError,
ProviderAuthenticationError,
ProviderTimeoutError,
UnsupportedFormatError,
UnsupportedLanguageError,
QuotaExceededError,
RateLimitExceededError,
TranscriptionError
)
class TestAzureSpeechIntegration:
"""Integration tests for Azure Speech provider with system components."""
@pytest.fixture
def mock_azure_sdk(self):
"""Mock Azure Speech SDK for integration tests."""
with patch('voice_control.providers.azure_speech_provider.AZURE_SPEECH_AVAILABLE', True):
with patch('voice_control.providers.azure_speech_provider.speechsdk') as mock_sdk:
# Mock all necessary components
mock_speech_config = Mock()
mock_sdk.SpeechConfig.return_value = mock_speech_config
mock_audio_config = Mock()
mock_sdk.audio.AudioConfig.return_value = mock_audio_config
mock_push_stream = Mock()
mock_sdk.audio.PushAudioInputStream.return_value = mock_push_stream
mock_recognizer = Mock()
mock_sdk.SpeechRecognizer.return_value = mock_recognizer
# Mock enums
mock_sdk.ResultReason.RecognizedSpeech = "RecognizedSpeech"
mock_sdk.ResultReason.NoMatch = "NoMatch"
mock_sdk.ResultReason.RecognizingSpeech = "RecognizingSpeech"
mock_sdk.CancellationReason.Error = "Error"
mock_sdk.OutputFormat.Detailed = "Detailed"
mock_sdk.ProfanityOption.Raw = "Raw"
mock_sdk.ProfanityOption.Masked = "Masked"
yield mock_sdk
@pytest.fixture
def provider_config(self):
"""Create provider configuration for integration tests."""
return ProviderConfig(
name="azure_integration",
provider_type=ProviderType.AZURE_SPEECH,
enabled=True,
priority=3,
free_tier_limits={
"audio_hours_per_month": 5.0,
"requests_per_minute": 20,
"requests_per_day": 5000
},
rate_limits={
"requests_per_minute": 20,
"requests_per_day": 5000
},
supported_formats=["wav", "flac", "mp3", "ogg", "webm"],
supported_languages=["en-US", "en-GB", "es-ES", "fr-FR", "de-DE"],
cost_per_minute=2.5 / 60.0,
api_credentials={
"subscription_key": "integration_test_key_12345",
"region": "eastus"
},
timeout_seconds=60,
max_retries=3
)
@pytest.fixture
def provider(self, provider_config, mock_azure_sdk):
"""Create Azure Speech provider for integration tests."""
return AzureSpeechProvider(provider_config)
@pytest.mark.asyncio
async def test_provider_manager_integration(self, provider, mock_azure_sdk):
"""Test integration with provider manager system."""
# Mock successful transcription
mock_result = Mock()
mock_result.reason = "RecognizedSpeech"
mock_result.text = "Provider manager integration test"
mock_result.json = json.dumps({
"NBest": [{
"Confidence": 0.88,
"Display": "Provider manager integration test",
"Words": [
{"Word": "Provider", "Offset": 0, "Duration": 5000000, "Confidence": 0.9},
{"Word": "manager", "Offset": 5000000, "Duration": 5000000, "Confidence": 0.85},
{"Word": "integration", "Offset": 10000000, "Duration": 8000000, "Confidence": 0.9},
{"Word": "test", "Offset": 18000000, "Duration": 4000000, "Confidence": 0.87}
]
}]
})
mock_recognizer = mock_azure_sdk.SpeechRecognizer.return_value
mock_recognizer.recognize_once.return_value = mock_result
# Test transcription through provider interface
audio_data = b"provider_manager_test_audio"
result = await provider.transcribe_audio(
audio_data,
"wav",
"en-US",
enable_word_timestamps=True
)
# Verify provider manager compatible result
assert isinstance(result, TranscriptionResult)
assert result.text == "Provider manager integration test"
assert result.confidence == 0.88
assert result.provider == "azure_integration"
assert result.language == "en-US"
assert result.is_final
assert len(result.word_timestamps) == 4
# Verify word timestamps are properly formatted
assert result.word_timestamps[0].word == "Provider"
assert result.word_timestamps[0].start_time == 0.0
assert result.word_timestamps[0].end_time == 0.5
assert result.word_timestamps[0].confidence == 0.9
@pytest.mark.asyncio
async def test_fallback_chain_integration(self, provider, mock_azure_sdk):
"""Test provider behavior in fallback chain scenarios."""
# Test 1: Provider available and working
mock_result = Mock()
mock_result.reason = "RecognizedSpeech"
mock_result.text = "Fallback test success"
mock_result.json = json.dumps({
"NBest": [{"Confidence": 0.92, "Display": "Fallback test success"}]
})
mock_recognizer = mock_azure_sdk.SpeechRecognizer.return_value
mock_recognizer.recognize_once.return_value = mock_result
# Should work normally
health = await provider.check_health()
assert health is True
result = await provider.transcribe_audio(b"test_audio", "wav", "en-US")
assert result.text == "Fallback test success"
# Test 2: Provider failure (should raise appropriate exception for fallback)
mock_recognizer.recognize_once.side_effect = Exception("Service temporarily unavailable")
with pytest.raises(TranscriptionError):
await provider.transcribe_audio(b"test_audio", "wav", "en-US")
# Health check should also fail
health = await provider.check_health()
assert health is False
@pytest.mark.asyncio
async def test_rate_limiter_integration(self, provider, mock_azure_sdk):
"""Test integration with rate limiting system."""
# Mock successful transcription
mock_result = Mock()
mock_result.reason = "RecognizedSpeech"
mock_result.text = "Rate limit test"
mock_result.json = json.dumps({
"NBest": [{"Confidence": 0.9, "Display": "Rate limit test"}]
})
mock_recognizer = mock_azure_sdk.SpeechRecognizer.return_value
mock_recognizer.recognize_once.return_value = mock_result
# Test quota checking before requests
quota_status = await provider.get_quota_status()
initial_minute_usage = quota_status["requests_per_minute"].current_usage
initial_daily_usage = quota_status["requests_per_day"].current_usage
# Make a request
result = await provider.transcribe_audio(b"test_audio", "wav", "en-US")
assert result.text == "Rate limit test"
# Verify quota was consumed
quota_status = await provider.get_quota_status()
assert quota_status["requests_per_minute"].current_usage == initial_minute_usage + 1
assert quota_status["requests_per_day"].current_usage == initial_daily_usage + 1
# Test rate limit enforcement
provider._usage_stats["requests_this_minute"] = 20 # At limit
with pytest.raises(RateLimitExceededError) as exc_info:
await provider.transcribe_audio(b"test_audio", "wav", "en-US")
assert exc_info.value.provider == "azure_integration"
assert exc_info.value.retry_after == 60.0
@pytest.mark.asyncio
async def test_audio_processor_integration(self, provider, mock_azure_sdk):
"""Test integration with audio processing components."""
# Mock successful transcription
mock_result = Mock()
mock_result.reason = "RecognizedSpeech"
mock_result.text = "Audio processing integration test"
mock_result.json = json.dumps({
"NBest": [{"Confidence": 0.87, "Display": "Audio processing integration test"}]
})
mock_recognizer = mock_azure_sdk.SpeechRecognizer.return_value
mock_recognizer.recognize_once.return_value = mock_result
# Test different audio formats
test_formats = ["wav", "mp3", "flac", "webm"]
for format_type in test_formats:
if provider.supports_format(format_type):
audio_data = b"test_audio_" + format_type.encode()
result = await provider.transcribe_audio(
audio_data,
format_type,
"en-US",
audio_duration=2.5 # Provide duration for testing
)
assert result.text == "Audio processing integration test"
assert result.audio_duration == 2.5
# Verify format-specific processing
mock_azure_sdk.SpeechConfig.assert_called()
mock_azure_sdk.SpeechRecognizer.assert_called()
@pytest.mark.asyncio
async def test_cache_manager_integration(self, provider, mock_azure_sdk):
"""Test integration with caching system."""
# Mock successful transcription
mock_result = Mock()
mock_result.reason = "RecognizedSpeech"
mock_result.text = "Cache integration test"
mock_result.json = json.dumps({
"NBest": [{"Confidence": 0.91, "Display": "Cache integration test"}]
})
mock_recognizer = mock_azure_sdk.SpeechRecognizer.return_value
mock_recognizer.recognize_once.return_value = mock_result
# Test transcription (should be cacheable)
audio_data = b"cacheable_audio_data"
result1 = await provider.transcribe_audio(audio_data, "wav", "en-US")
assert result1.text == "Cache integration test"
# Second request with same audio (cache system would handle this)
result2 = await provider.transcribe_audio(audio_data, "wav", "en-US")
assert result2.text == "Cache integration test"
# Both results should have consistent metadata for caching
assert result1.provider == result2.provider
assert result1.language == result2.language
assert result1.confidence == result2.confidence
@pytest.mark.asyncio
async def test_cost_monitor_integration(self, provider, mock_azure_sdk):
"""Test integration with cost monitoring system."""
# Mock successful transcription
mock_result = Mock()
mock_result.reason = "RecognizedSpeech"
mock_result.text = "Cost monitoring test"
mock_result.json = json.dumps({
"NBest": [{"Confidence": 0.89, "Display": "Cost monitoring test"}]
})
mock_recognizer = mock_azure_sdk.SpeechRecognizer.return_value
mock_recognizer.recognize_once.return_value = mock_result
# Test cost estimation
audio_duration = 3600.0 # 1 hour
estimated_cost = await provider.estimate_cost(audio_duration)
# Should be free within 5-hour limit
assert estimated_cost == 0.0
# Test cost for exceeding free tier
audio_duration = 6 * 3600.0 # 6 hours
estimated_cost = await provider.estimate_cost(audio_duration)
# Should charge for 1 hour at neural pricing
expected_cost = 1 * 2.5 # 1 hour * $2.50/hour
assert estimated_cost == expected_cost
# Test actual usage tracking
initial_usage = provider._usage_stats["audio_hours_this_month"]
result = await provider.transcribe_audio(
b"cost_test_audio",
"wav",
"en-US",
audio_duration=1800.0 # 30 minutes
)
# Verify usage was tracked
final_usage = provider._usage_stats["audio_hours_this_month"]
assert final_usage > initial_usage
assert final_usage == initial_usage + 0.5 # 30 minutes = 0.5 hours
@pytest.mark.asyncio
async def test_streaming_integration(self, provider, mock_azure_sdk):
"""Test streaming transcription integration."""
# Mock streaming components
mock_push_stream = Mock()
mock_azure_sdk.audio.PushAudioInputStream.return_value = mock_push_stream
mock_recognizer = mock_azure_sdk.SpeechRecognizer.return_value
mock_recognizer.recognized = Mock()
mock_recognizer.recognizing = Mock()
mock_recognizer.start_continuous_recognition = Mock()
mock_recognizer.stop_continuous_recognition = Mock()
# Create test audio stream
async def test_audio_stream():
chunks = [
b"chunk_1_audio_data",
b"chunk_2_audio_data",
b"chunk_3_audio_data",
b"final_chunk_audio"
]
for chunk in chunks:
yield chunk
await asyncio.sleep(0.1) # Simulate streaming delay
# Test streaming transcription
session_id = "test_streaming_session"
results = []
async for result in provider.transcribe_streaming(
test_audio_stream(),
"wav",
"en-US",
session_id=session_id,
interim_results=True
):
results.append(result)
# Verify streaming setup was called
mock_push_stream.write.assert_called()
mock_push_stream.close.assert_called_once()
mock_recognizer.start_continuous_recognition.assert_called_once()
mock_recognizer.stop_continuous_recognition.assert_called_once()
# Verify session was tracked
assert session_id not in provider._active_streams # Should be cleaned up
@pytest.mark.asyncio
async def test_error_handling_integration(self, provider, mock_azure_sdk):
"""Test comprehensive error handling integration."""
# Test authentication error
mock_recognizer = mock_azure_sdk.SpeechRecognizer.return_value
mock_recognizer.recognize_once.side_effect = Exception("unauthorized access denied")
with pytest.raises(ProviderAuthenticationError):
await provider.transcribe_audio(b"test_audio", "wav", "en-US")
# Test rate limit error
mock_recognizer.recognize_once.side_effect = Exception("rate limit exceeded, please try again")
with pytest.raises(RateLimitExceededError):
await provider.transcribe_audio(b"test_audio", "wav", "en-US")
# Test timeout error
mock_recognizer.recognize_once.side_effect = Exception("request timed out after 60 seconds")
with pytest.raises(ProviderTimeoutError):
await provider.transcribe_audio(b"test_audio", "wav", "en-US")
# Test service unavailable error
mock_recognizer.recognize_once.side_effect = Exception("service temporarily unavailable")
with pytest.raises(ProviderUnavailableError):
await provider.transcribe_audio(b"test_audio", "wav", "en-US")
# Test generic error
mock_recognizer.recognize_once.side_effect = Exception("unknown internal error")
with pytest.raises(TranscriptionError):
await provider.transcribe_audio(b"test_audio", "wav", "en-US")
@pytest.mark.asyncio
async def test_multi_language_integration(self, provider, mock_azure_sdk):
"""Test multi-language support integration."""
# Mock successful transcription for different languages
mock_result = Mock()
mock_result.reason = "RecognizedSpeech"
mock_result.json = json.dumps({
"NBest": [{"Confidence": 0.85, "Display": "Multi-language test"}]
})
mock_recognizer = mock_azure_sdk.SpeechRecognizer.return_value
mock_recognizer.recognize_once.return_value = mock_result
# Test supported languages
test_languages = ["en-US", "en-GB", "es-ES", "fr-FR", "de-DE"]
for language in test_languages:
if provider.supports_language(language):
mock_result.text = f"Test in {language}"
result = await provider.transcribe_audio(
b"multilingual_test_audio",
"wav",
language
)
assert result.text == f"Test in {language}"
assert result.language == language
assert result.confidence == 0.85
# Test unsupported language
with pytest.raises(UnsupportedLanguageError):
await provider.transcribe_audio(b"test_audio", "wav", "xx-XX")
@pytest.mark.asyncio
async def test_quota_reset_integration(self, provider, mock_azure_sdk):
"""Test quota reset timing integration."""
# Set up initial usage
provider._usage_stats["requests_this_minute"] = 10
provider._usage_stats["requests_today"] = 100
provider._usage_stats["audio_hours_this_month"] = 2.5
# Set timestamps to trigger resets
now = datetime.now(timezone.utc)
provider._usage_stats["last_minute_reset"] = now - timedelta(minutes=2)
provider._usage_stats["last_daily_reset"] = now.date() - timedelta(days=1)
provider._usage_stats["last_monthly_reset"] = now - timedelta(days=32)
# Check quota status (should trigger resets)
quota_status = await provider.get_quota_status()
# Verify resets occurred
assert provider._usage_stats["requests_this_minute"] == 0
assert provider._usage_stats["requests_today"] == 0
assert provider._usage_stats["audio_hours_this_month"] == 0.0
# Verify quota status reflects resets
assert quota_status["requests_per_minute"].current_usage == 0
assert quota_status["requests_per_day"].current_usage == 0
assert quota_status["audio_hours_per_month"].current_usage == 0.0
@pytest.mark.asyncio
async def test_configuration_integration(self, mock_azure_sdk):
"""Test provider configuration integration."""
# Test with custom endpoint configuration
custom_config = ProviderConfig(
name="azure_custom_endpoint",
provider_type=ProviderType.AZURE_SPEECH,
enabled=True,
priority=1,
free_tier_limits={"audio_hours_per_month": 10.0, "requests_per_minute": 50},
rate_limits={"requests_per_minute": 50},
supported_formats=["wav", "mp3"],
supported_languages=["en-US", "es-ES"],
cost_per_minute=1.0 / 60.0, # Standard pricing
api_credentials={
"subscription_key": "custom_key",
"endpoint": "https://custom.cognitiveservices.azure.com/"
},
timeout_seconds=30,
max_retries=2
)
provider = AzureSpeechProvider(custom_config)
# Verify configuration was applied
assert provider.name == "azure_custom_endpoint"
assert provider.config.priority == 1
assert provider.config.free_tier_limits["audio_hours_per_month"] == 10.0
assert provider.config.api_credentials["endpoint"] == "https://custom.cognitiveservices.azure.com/"
# Test initialization with custom endpoint
await provider._initialize_client()
assert provider._client_initialized
# Verify custom limits are used
quota_status = await provider.get_quota_status()
assert quota_status["requests_per_minute"].limit == 50
assert quota_status["audio_hours_per_month"].limit == 10.0
class TestAzureSpeechProviderFactoryIntegration:
"""Integration tests for Azure Speech provider factory."""
@patch('voice_control.providers.azure_speech_provider.AZURE_SPEECH_AVAILABLE', True)
def test_factory_integration_with_provider_manager(self):
"""Test factory function integration with provider manager."""
# Create provider using factory
provider = create_azure_speech_provider(
name="factory_test_azure",
priority=2,
api_credentials={
"subscription_key": "factory_test_key",
"region": "westus2"
}
)
# Verify provider is properly configured for provider manager
assert isinstance(provider, AzureSpeechProvider)
assert provider.name == "factory_test_azure"
assert provider.config.priority == 2
assert provider.config.provider_type == ProviderType.AZURE_SPEECH
assert provider.config.enabled
# Verify it has all required interface methods
assert hasattr(provider, 'transcribe_audio')
assert hasattr(provider, 'transcribe_streaming')
assert hasattr(provider, 'check_health')
assert hasattr(provider, 'get_quota_status')
assert hasattr(provider, 'supports_format')
assert hasattr(provider, 'supports_language')
assert hasattr(provider, 'estimate_cost')
# Verify configuration is compatible with system
assert len(provider.config.supported_formats) > 0
assert len(provider.config.supported_languages) > 0
assert provider.config.cost_per_minute >= 0
assert provider.config.timeout_seconds > 0
if __name__ == "__main__":
pytest.main([__file__])