File size: 12,389 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
"""
Unit tests for voice control data models.

This module tests the data models defined in voice_control.models,
ensuring proper validation, initialization, and behavior.
"""

import pytest
from datetime import datetime, timedelta
from hypothesis import given, strategies as st

from voice_control.models import (
    ProviderConfig, ProviderType, TranscriptionResult, UsageStats,
    ProviderStatus, ProcessedAudio, QuotaStatus, QuotaType,
    CacheStats, CostSummary, BudgetAlert, WordTimestamp, AudioSegment
)
from voice_control.tests.conftest import (
    provider_config_strategy, transcription_result_strategy, quota_status_strategy
)


class TestProviderConfig:
    """Test cases for ProviderConfig model."""
    
    def test_valid_provider_config_creation(self, sample_provider_config):
        """Test creating a valid provider configuration."""
        config = sample_provider_config
        assert config.name == "test_provider"
        assert config.provider_type == ProviderType.WEB_SPEECH_API
        assert config.enabled is True
        assert config.priority == 1
        assert "webm" in config.supported_formats
        assert "en-US" in config.supported_languages
    
    def test_invalid_priority_raises_error(self):
        """Test that negative priority raises ValueError."""
        with pytest.raises(ValueError, match="Priority must be non-negative"):
            ProviderConfig(
                name="test",
                provider_type=ProviderType.WEB_SPEECH_API,
                enabled=True,
                priority=-1,  # Invalid
                free_tier_limits={},
                rate_limits={},
                supported_formats=["wav"],
                supported_languages=["en-US"],
                cost_per_minute=0.0,
                api_credentials={}
            )
    
    def test_invalid_cost_raises_error(self):
        """Test that negative cost raises ValueError."""
        with pytest.raises(ValueError, match="Cost per minute must be non-negative"):
            ProviderConfig(
                name="test",
                provider_type=ProviderType.WEB_SPEECH_API,
                enabled=True,
                priority=1,
                free_tier_limits={},
                rate_limits={},
                supported_formats=["wav"],
                supported_languages=["en-US"],
                cost_per_minute=-0.1,  # Invalid
                api_credentials={}
            )
    
    def test_empty_formats_raises_error(self):
        """Test that empty supported formats raises ValueError."""
        with pytest.raises(ValueError, match="At least one supported format must be specified"):
            ProviderConfig(
                name="test",
                provider_type=ProviderType.WEB_SPEECH_API,
                enabled=True,
                priority=1,
                free_tier_limits={},
                rate_limits={},
                supported_formats=[],  # Invalid
                supported_languages=["en-US"],
                cost_per_minute=0.0,
                api_credentials={}
            )
    
    @given(provider_config_strategy())
    def test_provider_config_property_validation(self, config):
        """Property test: All generated configs should be valid."""
        # If we get here without exception, the config is valid
        assert config.priority >= 0
        assert config.cost_per_minute >= 0
        assert len(config.supported_formats) > 0


class TestTranscriptionResult:
    """Test cases for TranscriptionResult model."""
    
    def test_valid_transcription_result(self, sample_transcription_result):
        """Test creating a valid transcription result."""
        result = sample_transcription_result
        assert result.text == "Hello world"
        assert result.confidence == 0.95
        assert result.provider == "test_provider"
        assert result.is_final is True
    
    def test_invalid_confidence_raises_error(self):
        """Test that invalid confidence values raise ValueError."""
        with pytest.raises(ValueError, match="Confidence must be between 0 and 1"):
            TranscriptionResult(
                text="test",
                confidence=1.5,  # Invalid
                provider="test",
                processing_time=1.0,
                audio_duration=1.0,
                language="en-US"
            )
        
        with pytest.raises(ValueError, match="Confidence must be between 0 and 1"):
            TranscriptionResult(
                text="test",
                confidence=-0.1,  # Invalid
                provider="test",
                processing_time=1.0,
                audio_duration=1.0,
                language="en-US"
            )
    
    def test_invalid_processing_time_raises_error(self):
        """Test that negative processing time raises ValueError."""
        with pytest.raises(ValueError, match="Processing time must be non-negative"):
            TranscriptionResult(
                text="test",
                confidence=0.9,
                provider="test",
                processing_time=-1.0,  # Invalid
                audio_duration=1.0,
                language="en-US"
            )
    
    def test_invalid_audio_duration_raises_error(self):
        """Test that negative audio duration raises ValueError."""
        with pytest.raises(ValueError, match="Audio duration must be non-negative"):
            TranscriptionResult(
                text="test",
                confidence=0.9,
                provider="test",
                processing_time=1.0,
                audio_duration=-1.0,  # Invalid
                language="en-US"
            )
    
    @given(transcription_result_strategy())
    def test_transcription_result_property_validation(self, result):
        """Property test: All generated results should be valid."""
        assert 0.0 <= result.confidence <= 1.0
        assert result.processing_time >= 0.0
        assert result.audio_duration >= 0.0


class TestQuotaStatus:
    """Test cases for QuotaStatus model."""
    
    def test_quota_status_calculations(self):
        """Test quota status calculations and properties."""
        quota = QuotaStatus(
            provider="test",
            quota_type=QuotaType.REQUESTS_PER_MINUTE,
            current_usage=75,
            limit=100,
            remaining=25,
            reset_time=datetime.utcnow() + timedelta(minutes=1),
            percentage_used=0.75
        )
        
        assert quota.percentage_used == 0.75
        assert quota.remaining == 25
        assert not quota.is_exceeded
        assert quota.is_near_limit(threshold=0.7)
    
    def test_quota_exceeded(self):
        """Test quota exceeded detection."""
        quota = QuotaStatus(
            provider="test",
            quota_type=QuotaType.REQUESTS_PER_MINUTE,
            current_usage=110,
            limit=100,
            remaining=0,
            reset_time=datetime.utcnow() + timedelta(minutes=1),
            percentage_used=1.0
        )
        
        assert quota.is_exceeded
        assert quota.percentage_used == 1.0
        assert quota.remaining == 0
    
    def test_zero_limit_handling(self):
        """Test handling of zero limits."""
        quota = QuotaStatus(
            provider="test",
            quota_type=QuotaType.REQUESTS_PER_MINUTE,
            current_usage=10,
            limit=0,
            remaining=0,
            reset_time=datetime.utcnow() + timedelta(minutes=1),
            percentage_used=0.0
        )
        
        assert quota.percentage_used == 0.0
        assert quota.remaining == 0.0
    
    @given(quota_status_strategy())
    def test_quota_status_property_validation(self, quota):
        """Property test: All generated quota statuses should be valid."""
        assert quota.current_usage >= 0
        assert quota.limit >= 0
        assert quota.remaining >= 0
        assert 0.0 <= quota.percentage_used <= 1.0


class TestAudioSegment:
    """Test cases for AudioSegment model."""
    
    def test_valid_audio_segment(self):
        """Test creating a valid audio segment."""
        segment = AudioSegment(
            data=b"audio_data",
            start_time=0.0,
            end_time=1.0,
            sample_rate=44100,
            channels=2,
            format="wav"
        )
        
        assert segment.duration == 1.0
        assert segment.sample_rate == 44100
        assert segment.channels == 2
    
    def test_invalid_time_range_raises_error(self):
        """Test that invalid time ranges raise ValueError."""
        with pytest.raises(ValueError, match="End time must be greater than start time"):
            AudioSegment(
                data=b"audio_data",
                start_time=1.0,
                end_time=0.5,  # Invalid: end < start
                sample_rate=44100,
                channels=2,
                format="wav"
            )
    
    def test_negative_start_time_raises_error(self):
        """Test that negative start time raises ValueError."""
        with pytest.raises(ValueError, match="Start time must be non-negative"):
            AudioSegment(
                data=b"audio_data",
                start_time=-1.0,  # Invalid
                end_time=1.0,
                sample_rate=44100,
                channels=2,
                format="wav"
            )


class TestCacheStats:
    """Test cases for CacheStats model."""
    
    def test_cache_stats_calculations(self):
        """Test cache statistics calculations."""
        stats = CacheStats(
            total_requests=100,
            cache_hits=80,
            cache_misses=20,
            hit_rate=0.0,  # Will be calculated
            total_size_bytes=1024000,
            entry_count=50,
            evictions=5
        )
        
        assert stats.hit_rate == 0.8
        assert abs(stats.miss_rate - 0.2) < 0.001  # Use approximate comparison for floating point
    
    def test_zero_requests_handling(self):
        """Test handling of zero total requests."""
        stats = CacheStats(
            total_requests=0,
            cache_hits=0,
            cache_misses=0,
            hit_rate=0.0,
            total_size_bytes=0,
            entry_count=0,
            evictions=0
        )
        
        assert stats.hit_rate == 0.0
        assert stats.miss_rate == 1.0
    
    def test_invalid_hit_miss_totals_raise_error(self):
        """Test that mismatched hits/misses/total raises ValueError."""
        with pytest.raises(ValueError, match="Total requests must equal hits plus misses"):
            CacheStats(
                total_requests=100,
                cache_hits=60,
                cache_misses=30,  # 60 + 30 != 100
                hit_rate=0.0,
                total_size_bytes=1024,
                entry_count=10,
                evictions=0
            )


class TestWordTimestamp:
    """Test cases for WordTimestamp model."""
    
    def test_valid_word_timestamp(self):
        """Test creating a valid word timestamp."""
        timestamp = WordTimestamp(
            word="hello",
            start_time=0.5,
            end_time=1.0,
            confidence=0.95
        )
        
        assert timestamp.word == "hello"
        assert timestamp.start_time == 0.5
        assert timestamp.end_time == 1.0
        assert timestamp.confidence == 0.95


class TestUsageStats:
    """Test cases for UsageStats model."""
    
    def test_valid_usage_stats(self, sample_usage_stats):
        """Test creating valid usage statistics."""
        stats = sample_usage_stats
        assert stats.provider == "test_provider"
        assert stats.requests_count == 100
        assert stats.audio_minutes == 50.5
        assert stats.success_rate == 0.98
    
    def test_invalid_success_rate_raises_error(self):
        """Test that invalid success rate raises ValueError."""
        now = datetime.utcnow()
        
        with pytest.raises(ValueError, match="Success rate must be between 0 and 1"):
            UsageStats(
                provider="test",
                requests_count=10,
                audio_minutes=5.0,
                estimated_cost=1.0,
                success_rate=1.5,  # Invalid
                average_latency=1.0,
                time_window="hour",
                window_start=now - timedelta(hours=1),
                window_end=now
            )