Spaces:
Runtime error
Runtime error
Download voice_control/tests/test_azure_speech_provider.py from nifty-coder/stemsplit-backend: direct link, hf CLI and curl.
- Browser
- Download file 28.9 kB
-
https://huggingface.co/spaces/nifty-coder/stemsplit-backend/resolve/main/voice_control/tests/test_azure_speech_provider.py
- Command line
-
hf download hf://spaces/nifty-coder/stemsplit-backend/voice_control/tests/test_azure_speech_provider.py
-
curl -L -o test_azure_speech_provider.py https://huggingface.co/spaces/nifty-coder/stemsplit-backend/resolve/main/voice_control/tests/test_azure_speech_provider.py
28.9 kB
| """ | |
| Unit tests for Azure Speech Services provider. | |
| This module contains comprehensive tests for the AzureSpeechProvider class, | |
| including transcription functionality, quota management, error handling, | |
| and integration 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 | |
| from voice_control.providers.azure_speech_provider import AzureSpeechProvider, create_azure_speech_provider | |
| from voice_control.models import ( | |
| ProviderConfig, | |
| TranscriptionResult, | |
| QuotaStatus, | |
| QuotaType, | |
| ProviderType | |
| ) | |
| from voice_control.exceptions import ( | |
| ProviderError, | |
| ProviderUnavailableError, | |
| ProviderAuthenticationError, | |
| ProviderTimeoutError, | |
| UnsupportedFormatError, | |
| UnsupportedLanguageError, | |
| QuotaExceededError, | |
| RateLimitExceededError, | |
| TranscriptionError | |
| ) | |
| class TestAzureSpeechProvider: | |
| """Test cases for AzureSpeechProvider.""" | |
| def mock_azure_sdk(self): | |
| """Mock Azure Speech SDK components.""" | |
| with patch('voice_control.providers.azure_speech_provider.AZURE_SPEECH_AVAILABLE', True): | |
| # Mock the individual imports | |
| with patch('voice_control.providers.azure_speech_provider.speechsdk') as mock_speechsdk, \ | |
| patch('voice_control.providers.azure_speech_provider.SpeechConfig') as mock_speech_config_class, \ | |
| patch('voice_control.providers.azure_speech_provider.AudioConfig') as mock_audio_config_class, \ | |
| patch('voice_control.providers.azure_speech_provider.SpeechRecognizer') as mock_recognizer_class, \ | |
| patch('voice_control.providers.azure_speech_provider.ResultReason') as mock_result_reason, \ | |
| patch('voice_control.providers.azure_speech_provider.CancellationReason') as mock_cancel_reason: | |
| # Mock SpeechConfig instances | |
| mock_speech_config = Mock() | |
| mock_speech_config_class.return_value = mock_speech_config | |
| # Mock AudioConfig instances | |
| mock_audio_config = Mock() | |
| mock_audio_config_class.return_value = mock_audio_config | |
| # Mock SpeechRecognizer instances | |
| mock_recognizer = Mock() | |
| mock_recognizer_class.return_value = mock_recognizer | |
| # Mock audio components | |
| mock_push_stream = Mock() | |
| mock_speechsdk.audio.PushAudioInputStream.return_value = mock_push_stream | |
| mock_speechsdk.audio.AudioConfig.return_value = mock_audio_config | |
| # Mock ResultReason enum values | |
| mock_result_reason.RecognizedSpeech = "RecognizedSpeech" | |
| mock_result_reason.NoMatch = "NoMatch" | |
| mock_result_reason.RecognizingSpeech = "RecognizingSpeech" | |
| # Mock CancellationReason enum values | |
| mock_cancel_reason.Error = "Error" | |
| # Mock OutputFormat | |
| mock_speechsdk.OutputFormat.Detailed = "Detailed" | |
| # Mock ProfanityOption | |
| mock_speechsdk.ProfanityOption.Raw = "Raw" | |
| mock_speechsdk.ProfanityOption.Masked = "Masked" | |
| # Create a mock SDK object with all the mocked components | |
| mock_sdk = Mock() | |
| mock_sdk.SpeechConfig = mock_speech_config_class | |
| mock_sdk.AudioConfig = mock_audio_config_class | |
| mock_sdk.SpeechRecognizer = mock_recognizer_class | |
| mock_sdk.ResultReason = mock_result_reason | |
| mock_sdk.CancellationReason = mock_cancel_reason | |
| mock_sdk.OutputFormat = mock_speechsdk.OutputFormat | |
| mock_sdk.ProfanityOption = mock_speechsdk.ProfanityOption | |
| mock_sdk.audio = mock_speechsdk.audio | |
| yield mock_sdk | |
| def provider_config(self): | |
| """Create a test provider configuration.""" | |
| return ProviderConfig( | |
| name="test_azure_speech", | |
| 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"], | |
| cost_per_minute=2.5 / 60.0, # Neural pricing per minute | |
| api_credentials={ | |
| "subscription_key": "test_key_12345", | |
| "region": "eastus" | |
| }, | |
| timeout_seconds=60, | |
| max_retries=3 | |
| ) | |
| def provider(self, provider_config, mock_azure_sdk): | |
| """Create a test Azure Speech provider instance.""" | |
| return AzureSpeechProvider(provider_config) | |
| def test_initialization_success(self, provider_config, mock_azure_sdk): | |
| """Test successful provider initialization.""" | |
| provider = AzureSpeechProvider(provider_config) | |
| assert provider.name == "test_azure_speech" | |
| assert provider.provider_type == ProviderType.AZURE_SPEECH | |
| assert not provider._client_initialized | |
| assert provider._usage_stats["requests_today"] == 0 | |
| assert provider._usage_stats["audio_hours_this_month"] == 0.0 | |
| def test_initialization_invalid_provider_type(self, provider_config, mock_azure_sdk): | |
| """Test initialization with invalid provider type.""" | |
| provider_config.provider_type = ProviderType.GOOGLE_SPEECH | |
| with pytest.raises(ValueError, match="Invalid provider type"): | |
| AzureSpeechProvider(provider_config) | |
| def test_initialization_missing_azure_sdk(self, provider_config): | |
| """Test initialization when Azure SDK is not available.""" | |
| with patch('voice_control.providers.azure_speech_provider.AZURE_SPEECH_AVAILABLE', False): | |
| with pytest.raises(ImportError, match="Azure Speech SDK not available"): | |
| AzureSpeechProvider(provider_config) | |
| async def test_initialize_client_success(self, provider, mock_azure_sdk): | |
| """Test successful client initialization.""" | |
| await provider._initialize_client() | |
| assert provider._client_initialized | |
| mock_azure_sdk.SpeechConfig.assert_called_once() | |
| async def test_initialize_client_missing_credentials(self, provider_config, mock_azure_sdk): | |
| """Test client initialization with missing credentials.""" | |
| provider_config.api_credentials = {} | |
| provider = AzureSpeechProvider(provider_config) | |
| with pytest.raises(ProviderAuthenticationError): | |
| await provider._initialize_client() | |
| async def test_initialize_client_with_endpoint(self, provider_config, mock_azure_sdk): | |
| """Test client initialization with custom endpoint.""" | |
| provider_config.api_credentials = { | |
| "subscription_key": "test_key", | |
| "endpoint": "https://custom.cognitiveservices.azure.com/" | |
| } | |
| provider = AzureSpeechProvider(provider_config) | |
| await provider._initialize_client() | |
| assert provider._client_initialized | |
| mock_azure_sdk.SpeechConfig.assert_called_once() | |
| def test_supports_format(self, provider): | |
| """Test audio format support checking.""" | |
| assert provider.supports_format("wav") | |
| assert provider.supports_format("WAV") # Case insensitive | |
| assert provider.supports_format("mp3") | |
| assert provider.supports_format("flac") | |
| assert provider.supports_format("webm") | |
| assert not provider.supports_format("xyz") | |
| assert not provider.supports_format("") | |
| def test_supports_language(self, provider): | |
| """Test language support checking.""" | |
| 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 not provider.supports_language("xx-XX") | |
| assert not provider.supports_language("") | |
| async def test_estimate_cost_free_tier(self, provider): | |
| """Test cost estimation within free tier.""" | |
| # 1 hour of audio (within 5-hour free tier) | |
| cost = await provider.estimate_cost(3600.0) | |
| assert cost == 0.0 | |
| async def test_estimate_cost_exceeds_free_tier(self, provider): | |
| """Test cost estimation exceeding free tier.""" | |
| # 6 hours of audio (exceeds 5-hour free tier) | |
| cost = await provider.estimate_cost(6 * 3600.0) | |
| expected_cost = 1 * 2.5 # 1 hour at $2.50/hour (neural pricing) | |
| assert cost == expected_cost | |
| async def test_transcribe_audio_success(self, provider, mock_azure_sdk): | |
| """Test successful audio transcription.""" | |
| # Mock recognition result | |
| mock_result = Mock() | |
| mock_result.reason = "RecognizedSpeech" | |
| mock_result.text = "Hello world" | |
| mock_result.json = json.dumps({ | |
| "NBest": [{ | |
| "Confidence": 0.95, | |
| "Display": "Hello world", | |
| "Words": [ | |
| {"Word": "Hello", "Offset": 0, "Duration": 5000000, "Confidence": 0.98}, | |
| {"Word": "world", "Offset": 5000000, "Duration": 5000000, "Confidence": 0.92} | |
| ] | |
| }] | |
| }) | |
| mock_recognizer = mock_azure_sdk.SpeechRecognizer.return_value | |
| mock_recognizer.recognize_once.return_value = mock_result | |
| # Test transcription | |
| audio_data = b"fake_audio_data" | |
| result = await provider.transcribe_audio(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 | |
| assert len(result.word_timestamps) == 2 | |
| assert result.word_timestamps[0].word == "Hello" | |
| assert result.word_timestamps[1].word == "world" | |
| async def test_transcribe_audio_no_match(self, provider, mock_azure_sdk): | |
| """Test transcription with no speech detected.""" | |
| # Mock no match result | |
| mock_result = Mock() | |
| mock_result.reason = "NoMatch" | |
| mock_result.text = "" | |
| mock_recognizer = mock_azure_sdk.SpeechRecognizer.return_value | |
| mock_recognizer.recognize_once.return_value = mock_result | |
| # Test transcription | |
| audio_data = b"silent_audio_data" | |
| result = await provider.transcribe_audio(audio_data, "wav", "en-US") | |
| assert result.text == "" | |
| assert result.confidence == 0.0 | |
| assert result.is_final | |
| async def test_transcribe_audio_unsupported_format(self, provider): | |
| """Test transcription with unsupported audio format.""" | |
| audio_data = b"fake_audio_data" | |
| with pytest.raises(UnsupportedFormatError): | |
| await provider.transcribe_audio(audio_data, "xyz", "en-US") | |
| async def test_transcribe_audio_unsupported_language(self, provider): | |
| """Test transcription with unsupported language.""" | |
| audio_data = b"fake_audio_data" | |
| with pytest.raises(UnsupportedLanguageError): | |
| await provider.transcribe_audio(audio_data, "wav", "xx-XX") | |
| async def test_transcribe_audio_quota_exceeded(self, provider, mock_azure_sdk): | |
| """Test transcription when quota is exceeded.""" | |
| # Set usage to exceed monthly limit | |
| provider._usage_stats["audio_hours_this_month"] = 5.0 # At limit | |
| audio_data = b"fake_audio_data" | |
| with pytest.raises(QuotaExceededError): | |
| await provider.transcribe_audio(audio_data, "wav", "en-US", audio_duration=3600.0) # 1 hour | |
| async def test_transcribe_audio_rate_limit_exceeded(self, provider, mock_azure_sdk): | |
| """Test transcription when rate limit is exceeded.""" | |
| # Set usage to exceed minute limit | |
| provider._usage_stats["requests_this_minute"] = 20 # At limit | |
| audio_data = b"fake_audio_data" | |
| with pytest.raises(RateLimitExceededError): | |
| await provider.transcribe_audio(audio_data, "wav", "en-US") | |
| async def test_transcribe_streaming_success(self, provider, mock_azure_sdk): | |
| """Test successful streaming transcription.""" | |
| # 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 async generator for audio stream | |
| async def audio_generator(): | |
| yield b"chunk1" | |
| yield b"chunk2" | |
| yield b"chunk3" | |
| # Test streaming | |
| results = [] | |
| async for result in provider.transcribe_streaming(audio_generator(), "wav", "en-US"): | |
| results.append(result) | |
| # Verify streaming setup | |
| 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() | |
| async def test_check_health_success(self, provider, mock_azure_sdk): | |
| """Test successful health check.""" | |
| # Mock successful recognition | |
| mock_result = Mock() | |
| mock_result.reason = "RecognizedSpeech" | |
| mock_recognizer = mock_azure_sdk.SpeechRecognizer.return_value | |
| mock_recognizer.recognize_once.return_value = mock_result | |
| health = await provider.check_health() | |
| assert health is True | |
| async def test_check_health_failure(self, provider, mock_azure_sdk): | |
| """Test health check failure.""" | |
| # Mock recognition failure | |
| mock_recognizer = mock_azure_sdk.SpeechRecognizer.return_value | |
| mock_recognizer.recognize_once.side_effect = Exception("Service unavailable") | |
| health = await provider.check_health() | |
| assert health is False | |
| async def test_get_quota_status(self, provider): | |
| """Test quota status retrieval.""" | |
| # Set some usage | |
| provider._usage_stats["requests_this_minute"] = 5 | |
| provider._usage_stats["requests_today"] = 100 | |
| provider._usage_stats["audio_hours_this_month"] = 2.5 | |
| quota_status = await provider.get_quota_status() | |
| assert "requests_per_minute" in quota_status | |
| assert "requests_per_day" in quota_status | |
| assert "audio_hours_per_month" in quota_status | |
| minute_quota = quota_status["requests_per_minute"] | |
| assert minute_quota.current_usage == 5 | |
| assert minute_quota.limit == 20 | |
| assert minute_quota.remaining == 15 | |
| assert minute_quota.percentage_used == 0.25 | |
| monthly_quota = quota_status["audio_hours_per_month"] | |
| assert monthly_quota.current_usage == 2.5 | |
| assert monthly_quota.limit == 5.0 | |
| assert monthly_quota.remaining == 2.5 | |
| assert monthly_quota.percentage_used == 0.5 | |
| async def test_reset_counters_minute(self, provider): | |
| """Test minute counter reset.""" | |
| # Set usage and old timestamp | |
| provider._usage_stats["requests_this_minute"] = 10 | |
| provider._usage_stats["last_minute_reset"] = datetime.now(timezone.utc) - timedelta(minutes=2) | |
| await provider._reset_counters_if_needed() | |
| assert provider._usage_stats["requests_this_minute"] == 0 | |
| async def test_reset_counters_daily(self, provider): | |
| """Test daily counter reset.""" | |
| # Set usage and old timestamp | |
| provider._usage_stats["requests_today"] = 100 | |
| provider._usage_stats["last_daily_reset"] = datetime.now(timezone.utc).date() - timedelta(days=1) | |
| await provider._reset_counters_if_needed() | |
| assert provider._usage_stats["requests_today"] == 0 | |
| async def test_reset_counters_monthly(self, provider): | |
| """Test monthly counter reset.""" | |
| # Set usage and old timestamp | |
| provider._usage_stats["audio_hours_this_month"] = 3.0 | |
| provider._usage_stats["last_monthly_reset"] = datetime.now(timezone.utc) - timedelta(days=32) | |
| await provider._reset_counters_if_needed() | |
| assert provider._usage_stats["audio_hours_this_month"] == 0.0 | |
| def test_estimate_audio_duration_wav(self, provider): | |
| """Test audio duration estimation for WAV format.""" | |
| audio_data = b"x" * 32000 # 32KB of data | |
| duration = provider._estimate_audio_duration(audio_data, "wav") | |
| expected = 32000 / (16000 * 2) # 16kHz, 16-bit | |
| assert duration == expected | |
| def test_estimate_audio_duration_mp3(self, provider): | |
| """Test audio duration estimation for MP3 format.""" | |
| audio_data = b"x" * 8000 # 8KB of data | |
| duration = provider._estimate_audio_duration(audio_data, "mp3") | |
| expected = 8000 / 8000 # Compressed format estimation | |
| assert duration == expected | |
| async def test_handle_azure_error_authentication(self, provider): | |
| """Test handling of authentication errors.""" | |
| error = Exception("unauthorized access") | |
| with pytest.raises(ProviderAuthenticationError): | |
| await provider._handle_azure_error(error) | |
| async def test_handle_azure_error_rate_limit(self, provider): | |
| """Test handling of rate limit errors.""" | |
| error = Exception("rate limit exceeded") | |
| with pytest.raises(RateLimitExceededError): | |
| await provider._handle_azure_error(error) | |
| async def test_handle_azure_error_timeout(self, provider): | |
| """Test handling of timeout errors.""" | |
| error = Exception("request timed out") | |
| with pytest.raises(ProviderTimeoutError): | |
| await provider._handle_azure_error(error) | |
| async def test_handle_azure_error_unavailable(self, provider): | |
| """Test handling of service unavailable errors.""" | |
| error = Exception("service unavailable") | |
| with pytest.raises(ProviderUnavailableError): | |
| await provider._handle_azure_error(error) | |
| async def test_handle_azure_error_generic(self, provider): | |
| """Test handling of generic errors.""" | |
| error = Exception("unknown error") | |
| with pytest.raises(TranscriptionError): | |
| await provider._handle_azure_error(error) | |
| def test_extract_word_timestamps_success(self, provider): | |
| """Test successful word timestamp extraction.""" | |
| detailed_result = { | |
| "NBest": [{ | |
| "Words": [ | |
| {"Word": "Hello", "Offset": 0, "Duration": 5000000, "Confidence": 0.98}, | |
| {"Word": "world", "Offset": 5000000, "Duration": 5000000, "Confidence": 0.92} | |
| ] | |
| }] | |
| } | |
| timestamps = provider._extract_word_timestamps(detailed_result) | |
| assert len(timestamps) == 2 | |
| assert timestamps[0].word == "Hello" | |
| assert timestamps[0].start_time == 0.0 | |
| assert timestamps[0].end_time == 0.5 | |
| assert timestamps[0].confidence == 0.98 | |
| assert timestamps[1].word == "world" | |
| assert timestamps[1].start_time == 0.5 | |
| assert timestamps[1].end_time == 1.0 | |
| assert timestamps[1].confidence == 0.92 | |
| def test_extract_word_timestamps_empty(self, provider): | |
| """Test word timestamp extraction with empty result.""" | |
| detailed_result = {} | |
| timestamps = provider._extract_word_timestamps(detailed_result) | |
| assert timestamps == [] | |
| detailed_result = {"NBest": []} | |
| timestamps = provider._extract_word_timestamps(detailed_result) | |
| assert timestamps == [] | |
| detailed_result = {"NBest": [{"Words": []}]} | |
| timestamps = provider._extract_word_timestamps(detailed_result) | |
| assert timestamps == [] | |
| def test_extract_word_timestamps_malformed(self, provider): | |
| """Test word timestamp extraction with malformed data.""" | |
| detailed_result = { | |
| "NBest": [{ | |
| "Words": [ | |
| {"Word": "Hello"}, # Missing timing info | |
| {"Offset": 1000000, "Duration": 2000000} # Missing word | |
| ] | |
| }] | |
| } | |
| # Should handle gracefully and return empty list | |
| timestamps = provider._extract_word_timestamps(detailed_result) | |
| assert len(timestamps) <= 2 # May extract partial data or return empty | |
| def test_get_next_month_start_december(self, provider): | |
| """Test next month calculation for December.""" | |
| with patch('voice_control.providers.azure_speech_provider.datetime') as mock_dt: | |
| mock_dt.now.return_value = datetime(2023, 12, 15, 10, 30, 0, tzinfo=timezone.utc) | |
| mock_dt.side_effect = lambda *args, **kw: datetime(*args, **kw) | |
| next_month = provider._get_next_month_start() | |
| expected = datetime(2024, 1, 1, 0, 0, 0, tzinfo=timezone.utc) | |
| assert next_month == expected | |
| def test_get_next_month_start_regular(self, provider): | |
| """Test next month calculation for regular months.""" | |
| with patch('voice_control.providers.azure_speech_provider.datetime') as mock_dt: | |
| mock_dt.now.return_value = datetime(2023, 6, 15, 10, 30, 0, tzinfo=timezone.utc) | |
| mock_dt.side_effect = lambda *args, **kw: datetime(*args, **kw) | |
| next_month = provider._get_next_month_start() | |
| expected = datetime(2023, 7, 1, 0, 0, 0, tzinfo=timezone.utc) | |
| assert next_month == expected | |
| class TestAzureSpeechProviderFactory: | |
| """Test cases for Azure Speech provider factory function.""" | |
| def test_create_azure_speech_provider_defaults(self): | |
| """Test factory function with default parameters.""" | |
| provider = create_azure_speech_provider() | |
| assert provider.name == "azure_speech" | |
| assert provider.config.priority == 3 | |
| assert provider.config.provider_type == ProviderType.AZURE_SPEECH | |
| assert provider.config.enabled | |
| assert provider.config.cost_per_minute == AzureSpeechProvider.PRICING["neural"] / 60.0 | |
| def test_create_azure_speech_provider_custom(self): | |
| """Test factory function with custom parameters.""" | |
| provider = create_azure_speech_provider( | |
| name="custom_azure", | |
| priority=1, | |
| enabled=False, | |
| api_credentials={ | |
| "subscription_key": "custom_key", | |
| "region": "westus" | |
| } | |
| ) | |
| assert provider.name == "custom_azure" | |
| assert provider.config.priority == 1 | |
| assert not provider.config.enabled | |
| assert provider.config.api_credentials["subscription_key"] == "custom_key" | |
| assert provider.config.api_credentials["region"] == "westus" | |
| class TestAzureSpeechProviderIntegration: | |
| """Integration tests for Azure Speech provider.""" | |
| def integration_config(self): | |
| """Create configuration for integration tests.""" | |
| return ProviderConfig( | |
| name="azure_integration_test", | |
| provider_type=ProviderType.AZURE_SPEECH, | |
| enabled=True, | |
| priority=1, | |
| free_tier_limits=AzureSpeechProvider.FREE_TIER_LIMITS, | |
| rate_limits={ | |
| "requests_per_minute": 20, | |
| "requests_per_day": 5000 | |
| }, | |
| supported_formats=AzureSpeechProvider.SUPPORTED_FORMATS, | |
| supported_languages=AzureSpeechProvider.SUPPORTED_LANGUAGES, | |
| cost_per_minute=AzureSpeechProvider.PRICING["neural"] / 60.0, | |
| api_credentials={ | |
| "subscription_key": "integration_test_key", | |
| "region": "eastus" | |
| }, | |
| timeout_seconds=30, | |
| max_retries=2 | |
| ) | |
| async def test_full_transcription_workflow(self, integration_config, mock_azure_sdk): | |
| """Test complete transcription workflow.""" | |
| # Mock successful recognition | |
| mock_result = Mock() | |
| mock_result.reason = "RecognizedSpeech" | |
| mock_result.text = "Integration test successful" | |
| mock_result.json = json.dumps({ | |
| "NBest": [{ | |
| "Confidence": 0.92, | |
| "Display": "Integration test successful" | |
| }] | |
| }) | |
| mock_recognizer = mock_azure_sdk.SpeechRecognizer.return_value | |
| mock_recognizer.recognize_once.return_value = mock_result | |
| # Create provider and test | |
| provider = AzureSpeechProvider(integration_config) | |
| # Test transcription | |
| audio_data = b"integration_test_audio_data" | |
| result = await provider.transcribe_audio(audio_data, "wav", "en-US") | |
| # Verify results | |
| assert result.text == "Integration test successful" | |
| assert result.confidence == 0.92 | |
| assert result.provider == "azure_integration_test" | |
| assert result.language == "en-US" | |
| assert result.processing_time > 0 | |
| # Verify usage was tracked | |
| assert provider._usage_stats["requests_today"] == 1 | |
| assert provider._usage_stats["requests_this_minute"] == 1 | |
| assert provider._usage_stats["audio_hours_this_month"] > 0 | |
| async def test_quota_management_workflow(self, integration_config, mock_azure_sdk): | |
| """Test quota management across multiple requests.""" | |
| provider = AzureSpeechProvider(integration_config) | |
| # Make multiple requests to test quota tracking | |
| for i in range(5): | |
| # Mock successful recognition | |
| mock_result = Mock() | |
| mock_result.reason = "RecognizedSpeech" | |
| mock_result.text = f"Request {i+1}" | |
| mock_result.json = json.dumps({ | |
| "NBest": [{"Confidence": 0.9, "Display": f"Request {i+1}"}] | |
| }) | |
| mock_recognizer = mock_azure_sdk.SpeechRecognizer.return_value | |
| mock_recognizer.recognize_once.return_value = mock_result | |
| # Transcribe | |
| audio_data = b"test_audio" | |
| result = await provider.transcribe_audio(audio_data, "wav", "en-US") | |
| assert result.text == f"Request {i+1}" | |
| # Check quota status | |
| quota_status = await provider.get_quota_status() | |
| minute_quota = quota_status["requests_per_minute"] | |
| assert minute_quota.current_usage == 5 | |
| assert minute_quota.remaining == 15 | |
| assert minute_quota.percentage_used == 0.25 | |
| # Verify usage stats | |
| assert provider._usage_stats["requests_today"] == 5 | |
| assert provider._usage_stats["requests_this_minute"] == 5 | |
| if __name__ == "__main__": | |
| pytest.main([__file__]) |