File size: 28,933 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
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
"""
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."""
    
    @pytest.fixture
    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
    
    @pytest.fixture
    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
        )
    
    @pytest.fixture
    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)
    
    @pytest.mark.asyncio
    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()
    
    @pytest.mark.asyncio
    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()
    
    @pytest.mark.asyncio
    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("")
    
    @pytest.mark.asyncio
    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
    
    @pytest.mark.asyncio
    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
    
    @pytest.mark.asyncio
    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"
    
    @pytest.mark.asyncio
    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
    
    @pytest.mark.asyncio
    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")
    
    @pytest.mark.asyncio
    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")
    
    @pytest.mark.asyncio
    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
    
    @pytest.mark.asyncio
    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")
    
    @pytest.mark.asyncio
    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()
    
    @pytest.mark.asyncio
    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
    
    @pytest.mark.asyncio
    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
    
    @pytest.mark.asyncio
    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
    
    @pytest.mark.asyncio
    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
    
    @pytest.mark.asyncio
    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
    
    @pytest.mark.asyncio
    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
    
    @pytest.mark.asyncio
    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)
    
    @pytest.mark.asyncio
    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)
    
    @pytest.mark.asyncio
    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)
    
    @pytest.mark.asyncio
    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)
    
    @pytest.mark.asyncio
    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."""
    
    @patch('voice_control.providers.azure_speech_provider.AZURE_SPEECH_AVAILABLE', True)
    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
    
    @patch('voice_control.providers.azure_speech_provider.AZURE_SPEECH_AVAILABLE', True)
    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."""
    
    @pytest.fixture
    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
        )
    
    @pytest.mark.asyncio
    @patch('voice_control.providers.azure_speech_provider.AZURE_SPEECH_AVAILABLE', True)
    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
    
    @pytest.mark.asyncio
    @patch('voice_control.providers.azure_speech_provider.AZURE_SPEECH_AVAILABLE', True)
    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__])