Spaces:
Runtime error
Runtime error
File size: 23,056 Bytes
8cbe6eb | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 | """
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__]) |