""" 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 )