Spaces:
Runtime error
Runtime error
Download voice_control/tests/test_cache_manager.py from nifty-coder/stemsplit-backend: direct link, hf CLI and curl.
- Browser
- Download file 45.9 kB
-
https://huggingface.co/spaces/nifty-coder/stemsplit-backend/resolve/main/voice_control/tests/test_cache_manager.py
- Command line
-
hf download hf://spaces/nifty-coder/stemsplit-backend/voice_control/tests/test_cache_manager.py
-
curl -L -o test_cache_manager.py https://huggingface.co/spaces/nifty-coder/stemsplit-backend/resolve/main/voice_control/tests/test_cache_manager.py
45.9 kB
"""
Unit tests for the CacheManager implementation.
Tests cover audio fingerprinting, LRU cache behavior, TTL expiration,
cache statistics tracking, and cache hit optimization.
"""
import asyncio
import pytest
import time
from datetime import datetime
from unittest.mock import AsyncMock, MagicMock, patch
from voice_control.cache_manager import CacheManager, CacheEntry, create_cache_manager
from voice_control.models import TranscriptionResult, CacheStats
from voice_control.exceptions import CacheError
class TestCacheEntry:
"""Test the CacheEntry data class."""
def test_cache_entry_creation(self):
"""Test creating a cache entry."""
result = TranscriptionResult(
text="hello world",
confidence=0.95,
provider="test_provider",
processing_time=1.0,
audio_duration=2.0,
language="en-US"
)
entry = CacheEntry(
result=result,
created_at=time.time(),
last_accessed=time.time(),
ttl=3600
)
assert entry.result == result
assert entry.ttl == 3600
assert entry.access_count == 0
assert entry.size_bytes > 0
def test_cache_entry_expiration(self):
"""Test cache entry expiration logic."""
result = TranscriptionResult(
text="test",
confidence=0.9,
provider="test",
processing_time=1.0,
audio_duration=1.0,
language="en-US"
)
# Create expired entry
entry = CacheEntry(
result=result,
created_at=time.time() - 7200, # 2 hours ago
last_accessed=time.time() - 3600, # 1 hour ago
ttl=3600 # 1 hour TTL
)
assert entry.is_expired
def test_cache_entry_touch(self):
"""Test updating entry access information."""
result = TranscriptionResult(
text="test",
confidence=0.9,
provider="test",
processing_time=1.0,
audio_duration=1.0,
language="en-US"
)
entry = CacheEntry(
result=result,
created_at=time.time(),
last_accessed=time.time(),
ttl=3600
)
initial_access_count = entry.access_count
initial_last_accessed = entry.last_accessed
time.sleep(0.01) # Small delay
entry.touch()
assert entry.access_count == initial_access_count + 1
assert entry.last_accessed > initial_last_accessed
class TestCacheManager:
"""Test the CacheManager class."""
@pytest.fixture
def cache_manager(self):
"""Create a cache manager for testing."""
return CacheManager(
max_size_mb=1, # Small size for testing
default_ttl=3600,
cleanup_interval=60
)
@pytest.fixture
def sample_result(self):
"""Create a sample transcription result."""
return TranscriptionResult(
text="hello world test transcription",
confidence=0.95,
provider="test_provider",
processing_time=1.5,
audio_duration=3.0,
language="en-US",
alternatives=["hello world", "hello word"]
)
@pytest.fixture
def sample_audio(self):
"""Create sample audio data."""
return b"fake_audio_data_for_testing" * 100
@pytest.mark.asyncio
async def test_audio_fingerprint_generation(self, cache_manager, sample_audio):
"""Test audio fingerprint generation."""
fingerprint1 = await cache_manager.generate_audio_fingerprint(sample_audio)
fingerprint2 = await cache_manager.generate_audio_fingerprint(sample_audio)
# Same audio should produce same fingerprint
assert fingerprint1 == fingerprint2
assert len(fingerprint1) == 64 # SHA-256 hex length
# Different audio should produce different fingerprint
different_audio = b"different_audio_data" * 100
fingerprint3 = await cache_manager.generate_audio_fingerprint(different_audio)
assert fingerprint1 != fingerprint3
@pytest.mark.asyncio
async def test_cache_transcription_and_retrieval(self, cache_manager, sample_result, sample_audio):
"""Test caching and retrieving transcription results."""
fingerprint = await cache_manager.generate_audio_fingerprint(sample_audio)
# Initially should be cache miss
cached_result = await cache_manager.get_cached_transcription(fingerprint)
assert cached_result is None
# Cache the result
success = await cache_manager.cache_transcription(fingerprint, sample_result)
assert success
# Should now be cache hit
cached_result = await cache_manager.get_cached_transcription(fingerprint)
assert cached_result is not None
assert cached_result.text == sample_result.text
assert cached_result.confidence == sample_result.confidence
assert cached_result.provider == sample_result.provider
@pytest.mark.asyncio
async def test_cache_ttl_expiration(self, cache_manager, sample_result, sample_audio):
"""Test TTL-based cache expiration."""
fingerprint = await cache_manager.generate_audio_fingerprint(sample_audio)
# Cache with very short TTL
success = await cache_manager.cache_transcription(fingerprint, sample_result, ttl=1)
assert success
# Should be available immediately
cached_result = await cache_manager.get_cached_transcription(fingerprint)
assert cached_result is not None
# Wait for expiration
await asyncio.sleep(1.1)
# Should now be expired
cached_result = await cache_manager.get_cached_transcription(fingerprint)
assert cached_result is None
@pytest.mark.asyncio
async def test_lru_eviction(self):
"""Test LRU (Least Recently Used) eviction policy."""
# Create cache manager with very small size to force eviction
cache_manager = CacheManager(max_size_mb=0.01) # 10KB only
# Create multiple large results that will exceed cache size
results = []
fingerprints = []
for i in range(5):
audio_data = f"audio_data_{i}".encode() * 2000 # Make it large
result = TranscriptionResult(
text=f"transcription_{i}" * 200, # Make text large
confidence=0.9,
provider="test",
processing_time=1.0,
audio_duration=1.0,
language="en-US"
)
fingerprint = await cache_manager.generate_audio_fingerprint(audio_data)
fingerprints.append(fingerprint)
results.append(result)
await cache_manager.cache_transcription(fingerprint, result)
# Access some entries to make them more recently used
await cache_manager.get_cached_transcription(fingerprints[3])
await cache_manager.get_cached_transcription(fingerprints[4])
# Add one more large entry to trigger eviction
large_audio = b"large_audio_data" * 5000
large_result = TranscriptionResult(
text="large transcription" * 500,
confidence=0.9,
provider="test",
processing_time=1.0,
audio_duration=1.0,
language="en-US"
)
large_fingerprint = await cache_manager.generate_audio_fingerprint(large_audio)
await cache_manager.cache_transcription(large_fingerprint, large_result)
# Some early entries should have been evicted
stats = await cache_manager.get_cache_stats()
assert stats.evictions > 0
# Recently accessed entries should still be available
cached_3 = await cache_manager.get_cached_transcription(fingerprints[3])
cached_4 = await cache_manager.get_cached_transcription(fingerprints[4])
# At least one should survive, or the large entry should be there
large_cached = await cache_manager.get_cached_transcription(large_fingerprint)
assert cached_3 is not None or cached_4 is not None or large_cached is not None
@pytest.mark.asyncio
async def test_cache_statistics(self, cache_manager, sample_result, sample_audio):
"""Test cache statistics tracking."""
fingerprint = await cache_manager.generate_audio_fingerprint(sample_audio)
# Initial stats
stats = await cache_manager.get_cache_stats()
initial_requests = stats.total_requests
# Cache miss
await cache_manager.get_cached_transcription(fingerprint)
# Cache the result
await cache_manager.cache_transcription(fingerprint, sample_result)
# Cache hit
await cache_manager.get_cached_transcription(fingerprint)
# Check updated stats
stats = await cache_manager.get_cache_stats()
assert stats.total_requests == initial_requests + 2
assert stats.cache_hits >= 1
assert stats.cache_misses >= 1
assert stats.entry_count >= 1
assert 0.0 <= stats.hit_rate <= 1.0
@pytest.mark.asyncio
async def test_clear_cache(self, cache_manager, sample_result, sample_audio):
"""Test clearing all cache entries."""
fingerprint = await cache_manager.generate_audio_fingerprint(sample_audio)
# Cache a result
await cache_manager.cache_transcription(fingerprint, sample_result)
# Verify it's cached
cached_result = await cache_manager.get_cached_transcription(fingerprint)
assert cached_result is not None
# Clear cache
await cache_manager.clear_cache()
# Verify it's gone
cached_result = await cache_manager.get_cached_transcription(fingerprint)
assert cached_result is None
# Check stats
stats = await cache_manager.get_cache_stats()
assert stats.entry_count == 0
assert stats.total_size_bytes == 0
@pytest.mark.asyncio
async def test_evict_expired(self, cache_manager):
"""Test manual expiration of expired entries."""
# Create results with different TTLs
results = []
fingerprints = []
for i in range(3):
audio_data = f"audio_{i}".encode()
result = TranscriptionResult(
text=f"text_{i}",
confidence=0.9,
provider="test",
processing_time=1.0,
audio_duration=1.0,
language="en-US"
)
fingerprint = await cache_manager.generate_audio_fingerprint(audio_data)
fingerprints.append(fingerprint)
results.append(result)
# Cache with different TTLs
ttl = 1 if i < 2 else 3600 # First two expire quickly
await cache_manager.cache_transcription(fingerprint, result, ttl=ttl)
# Wait for some to expire
await asyncio.sleep(1.1)
# Manually evict expired entries
evicted_count = await cache_manager.evict_expired()
assert evicted_count >= 2
# Non-expired entry should still be available
cached_result = await cache_manager.get_cached_transcription(fingerprints[2])
assert cached_result is not None
@pytest.mark.asyncio
async def test_context_manager(self):
"""Test using cache manager as async context manager."""
async with CacheManager() as cache_manager:
assert cache_manager._running
# Test basic functionality
audio_data = b"test_audio"
fingerprint = await cache_manager.generate_audio_fingerprint(audio_data)
assert len(fingerprint) == 64
# Should be stopped after context exit
assert not cache_manager._running
@pytest.mark.asyncio
async def test_concurrent_access(self, cache_manager):
"""Test concurrent cache access."""
async def cache_and_retrieve(index):
audio_data = f"audio_{index}".encode()
result = TranscriptionResult(
text=f"text_{index}",
confidence=0.9,
provider="test",
processing_time=1.0,
audio_duration=1.0,
language="en-US"
)
fingerprint = await cache_manager.generate_audio_fingerprint(audio_data)
await cache_manager.cache_transcription(fingerprint, result)
cached_result = await cache_manager.get_cached_transcription(fingerprint)
assert cached_result is not None
assert cached_result.text == f"text_{index}"
return fingerprint
# Run multiple concurrent operations
tasks = [cache_and_retrieve(i) for i in range(10)]
fingerprints = await asyncio.gather(*tasks)
# All should have succeeded
assert len(fingerprints) == 10
assert len(set(fingerprints)) == 10 # All unique
def test_get_cache_info(self, cache_manager):
"""Test getting cache information."""
info = cache_manager.get_cache_info()
assert "max_size_bytes" in info
assert "current_size_bytes" in info
assert "entry_count" in info
assert "default_ttl" in info
assert "cleanup_interval" in info
assert "running" in info
assert "stats" in info
assert info["max_size_bytes"] == 1 * 1024 * 1024 # 1MB
assert info["default_ttl"] == 3600
assert info["cleanup_interval"] == 60
class TestCacheManagerFactory:
"""Test the cache manager factory function."""
def test_create_in_memory_cache_manager(self):
"""Test creating in-memory cache manager."""
config = {
"max_size_mb": 50,
"default_ttl": 1800,
"cleanup_interval": 300
}
cache_manager = create_cache_manager(config)
assert isinstance(cache_manager, CacheManager)
assert cache_manager.max_size_bytes == 50 * 1024 * 1024
assert cache_manager.default_ttl == 1800
assert cache_manager.cleanup_interval == 300
@patch('voice_control.cache_manager.RedisCacheManager')
def test_create_redis_cache_manager(self, mock_redis_cache):
"""Test creating Redis cache manager."""
config = {
"redis_url": "redis://localhost:6379",
"default_ttl": 1800,
"max_connections": 20
}
cache_manager = create_cache_manager(config)
# Should have created RedisCacheManager
mock_redis_cache.assert_called_once_with(
redis_url="redis://localhost:6379",
default_ttl=1800,
max_connections=20
)
class TestErrorHandling:
"""Test error handling in cache manager."""
@pytest.mark.asyncio
async def test_fingerprint_generation_error(self):
"""Test handling errors in fingerprint generation."""
cache_manager = CacheManager()
# Mock hashlib to raise an exception
with patch('voice_control.cache_manager.hashlib.sha256') as mock_hasher:
mock_hasher.side_effect = Exception("Hash error")
with pytest.raises(CacheError) as exc_info:
await cache_manager.generate_audio_fingerprint(b"test_audio")
assert "fingerprint_generation" in str(exc_info.value)
@pytest.mark.asyncio
async def test_cache_operation_resilience(self):
"""Test that cache operations are resilient to errors."""
cache_manager = CacheManager()
sample_result = TranscriptionResult(
text="test",
confidence=0.9,
provider="test",
processing_time=1.0,
audio_duration=1.0,
language="en-US"
)
# Test with invalid fingerprint
result = await cache_manager.get_cached_transcription("")
assert result is None
# Test caching with None result (should handle gracefully)
success = await cache_manager.cache_transcription("test_key", sample_result)
assert success # Should not crash
@pytest.mark.integration
class TestCacheManagerIntegration:
"""Integration tests for cache manager with other components."""
@pytest.mark.asyncio
async def test_realistic_usage_pattern(self):
"""Test realistic usage pattern with multiple operations."""
async with CacheManager(max_size_mb=5, default_ttl=60) as cache_manager:
# Simulate multiple audio transcriptions
transcriptions = []
for i in range(20):
# Generate unique audio data
audio_data = f"audio_sample_{i}".encode() * (100 + i * 10)
# Generate fingerprint
fingerprint = await cache_manager.generate_audio_fingerprint(audio_data)
# Check cache first (should be miss initially)
cached_result = await cache_manager.get_cached_transcription(fingerprint)
if cached_result is None:
# Simulate transcription
result = TranscriptionResult(
text=f"Transcribed text for sample {i}",
confidence=0.85 + (i % 10) * 0.01,
provider="test_provider",
processing_time=1.0 + i * 0.1,
audio_duration=2.0 + i * 0.2,
language="en-US"
)
# Cache the result
await cache_manager.cache_transcription(fingerprint, result)
transcriptions.append((fingerprint, result))
else:
transcriptions.append((fingerprint, cached_result))
# Verify some results are cached
stats = await cache_manager.get_cache_stats()
assert stats.total_requests > 0
assert stats.entry_count > 0
# Test accessing some cached results
for fingerprint, expected_result in transcriptions[:5]:
cached_result = await cache_manager.get_cached_transcription(fingerprint)
if cached_result: # May have been evicted due to size limits
assert cached_result.text == expected_result.text
# Final stats check
final_stats = await cache_manager.get_cache_stats()
assert final_stats.total_requests >= stats.total_requests
assert 0.0 <= final_stats.hit_rate <= 1.0
@pytest.mark.integration
class TestCacheHitOptimization:
"""Tests for cache hit optimization functionality (Task 5.2)."""
@pytest.fixture
def cache_manager(self):
"""Create a cache manager for testing."""
return CacheManager(
max_size_mb=10,
default_ttl=3600,
cleanup_interval=60,
enable_stats=True
)
@pytest.fixture
def sample_audio_data(self):
"""Create sample audio data for testing."""
return b"sample_audio_data_for_cache_testing" * 50
@pytest.fixture
def sample_transcription_result(self):
"""Create a sample transcription result."""
return TranscriptionResult(
text="This is a sample transcription for cache testing",
confidence=0.95,
provider="test_provider",
processing_time=1.5,
audio_duration=3.0,
language="en-US",
alternatives=["alternative transcription"]
)
@pytest.mark.asyncio
async def test_cache_hit_avoids_api_calls(self, cache_manager, sample_audio_data, sample_transcription_result):
"""
Test that cache hits avoid API calls (Requirement 4.3).
**Validates: Requirements 4.3**
"""
async with cache_manager:
# Generate fingerprint
fingerprint = await cache_manager.generate_audio_fingerprint(sample_audio_data)
# Initial cache miss
cached_result = await cache_manager.get_cached_transcription(fingerprint)
assert cached_result is None
# Cache the transcription result
cache_success = await cache_manager.cache_transcription(fingerprint, sample_transcription_result)
assert cache_success
# Subsequent access should be cache hit (no API call needed)
cached_result = await cache_manager.get_cached_transcription(fingerprint)
assert cached_result is not None
assert cached_result.text == sample_transcription_result.text
assert cached_result.provider == sample_transcription_result.provider
assert cached_result.confidence == sample_transcription_result.confidence
# Verify cache statistics show the hit
stats = await cache_manager.get_cache_stats()
assert stats.cache_hits >= 1
assert stats.total_requests >= 2 # At least one miss + one hit
@pytest.mark.asyncio
async def test_cache_statistics_tracking(self, cache_manager):
"""
Test comprehensive cache statistics tracking.
**Validates: Requirements 4.3**
"""
async with cache_manager:
initial_stats = await cache_manager.get_cache_stats()
# Perform multiple cache operations
audio_samples = []
results = []
for i in range(5):
audio_data = f"audio_sample_{i}".encode() * 100
result = TranscriptionResult(
text=f"transcription_{i}",
confidence=0.9,
provider="test_provider",
processing_time=1.0,
audio_duration=2.0,
language="en-US"
)
fingerprint = await cache_manager.generate_audio_fingerprint(audio_data)
audio_samples.append((audio_data, fingerprint))
results.append(result)
# First access - cache miss
cached_result = await cache_manager.get_cached_transcription(fingerprint)
assert cached_result is None
# Cache the result
await cache_manager.cache_transcription(fingerprint, result)
# Second access - cache hit
cached_result = await cache_manager.get_cached_transcription(fingerprint)
assert cached_result is not None
# Check final statistics
final_stats = await cache_manager.get_cache_stats()
# Should have 5 misses (first access) + 5 hits (second access) = 10 total requests
assert final_stats.total_requests == initial_stats.total_requests + 10
assert final_stats.cache_hits == initial_stats.cache_hits + 5
assert final_stats.cache_misses == initial_stats.cache_misses + 5
assert final_stats.entry_count == initial_stats.entry_count + 5
# Hit rate should be exactly 50% for this test
expected_hit_rate = final_stats.cache_hits / final_stats.total_requests
assert abs(final_stats.hit_rate - expected_hit_rate) < 0.01
@pytest.mark.asyncio
async def test_detailed_cache_statistics(self, cache_manager):
"""
Test detailed cache statistics and optimization recommendations.
**Validates: Requirements 4.3**
"""
async with cache_manager:
# Perform various cache operations
for i in range(10):
audio_data = f"detailed_stats_audio_{i}".encode() * 100
result = TranscriptionResult(
text=f"detailed_stats_transcription_{i}",
confidence=0.9,
provider="test_provider",
processing_time=1.0,
audio_duration=2.0,
language="en-US"
)
fingerprint = await cache_manager.generate_audio_fingerprint(audio_data)
# Cache miss
await cache_manager.get_cached_transcription(fingerprint)
# Cache the result
await cache_manager.cache_transcription(fingerprint, result)
# Multiple cache hits to vary access patterns
for _ in range(i + 1): # Varying access counts
await cache_manager.get_cached_transcription(fingerprint)
# Get detailed statistics
detailed_stats = await cache_manager.get_detailed_cache_stats()
# Verify structure
assert "basic_stats" in detailed_stats
assert "size_stats" in detailed_stats
assert "performance_stats" in detailed_stats
assert "optimization_recommendations" in detailed_stats
# Verify basic stats
basic_stats = detailed_stats["basic_stats"]
assert basic_stats["total_requests"] > 0
assert basic_stats["cache_hits"] > 0
assert basic_stats["cache_misses"] > 0
assert 0.0 <= basic_stats["hit_rate"] <= 1.0
# Verify size stats
size_stats = detailed_stats["size_stats"]
assert size_stats["entry_count"] == 10
assert size_stats["total_size_bytes"] > 0
assert size_stats["avg_entry_size_bytes"] > 0
assert 0.0 <= size_stats["utilization_rate"] <= 1.0
# Verify performance stats
perf_stats = detailed_stats["performance_stats"]
assert "cache_efficiency" in perf_stats
assert "eviction_rate" in perf_stats
assert "access_patterns" in perf_stats
# Verify access patterns
access_patterns = perf_stats["access_patterns"]
assert access_patterns["most_accessed_entries"] > 0
assert access_patterns["avg_access_count"] > 0
# Verify recommendations exist
recommendations = detailed_stats["optimization_recommendations"]
assert isinstance(recommendations, list)
assert len(recommendations) > 0
@pytest.mark.asyncio
async def test_batch_cache_lookup(self, cache_manager):
"""
Test batch cache lookup optimization.
**Validates: Requirements 4.3**
"""
async with cache_manager:
# Prepare test data
fingerprints = []
results = []
for i in range(5):
audio_data = f"batch_test_audio_{i}".encode() * 100
result = TranscriptionResult(
text=f"batch_test_transcription_{i}",
confidence=0.9,
provider="test_provider",
processing_time=1.0,
audio_duration=2.0,
language="en-US"
)
fingerprint = await cache_manager.generate_audio_fingerprint(audio_data)
fingerprints.append(fingerprint)
results.append(result)
# Cache every other result
if i % 2 == 0:
await cache_manager.cache_transcription(fingerprint, result)
# Perform batch lookup
batch_results = await cache_manager.get_cached_transcription_batch(fingerprints)
# Verify results
assert len(batch_results) == 5
# Check that cached entries are found and non-cached are None
for i, fingerprint in enumerate(fingerprints):
if i % 2 == 0: # Should be cached
assert batch_results[fingerprint] is not None
assert batch_results[fingerprint].text == f"batch_test_transcription_{i}"
else: # Should not be cached
assert batch_results[fingerprint] is None
@pytest.mark.asyncio
async def test_cache_warming(self, cache_manager):
"""
Test cache warming functionality.
**Validates: Requirements 4.3**
"""
async with cache_manager:
# Prepare fingerprints for warming
fingerprints = []
for i in range(3):
audio_data = f"warming_test_audio_{i}".encode() * 100
fingerprint = await cache_manager.generate_audio_fingerprint(audio_data)
fingerprints.append(fingerprint)
# Mock transcription callback
async def mock_transcription_callback(fingerprint):
return TranscriptionResult(
text=f"warmed_transcription_{fingerprint[:8]}",
confidence=0.9,
provider="warming_provider",
processing_time=1.0,
audio_duration=2.0,
language="en-US"
)
# Warm cache
warming_results = await cache_manager.warm_cache(
fingerprints,
mock_transcription_callback
)
# Verify warming results
assert len(warming_results) == 3
for fingerprint in fingerprints:
assert warming_results[fingerprint] is True
# Verify entries are cached
for fingerprint in fingerprints:
cached_result = await cache_manager.get_cached_transcription(fingerprint)
assert cached_result is not None
assert cached_result.provider == "warming_provider"
@pytest.mark.asyncio
async def test_cache_performance_optimization(self, cache_manager):
"""
Test cache performance optimization operations.
**Validates: Requirements 4.3**
"""
async with cache_manager:
# Create entries with different access patterns
fingerprints = []
for i in range(20):
audio_data = f"optimization_test_audio_{i}".encode() * 100
result = TranscriptionResult(
text=f"optimization_test_transcription_{i}",
confidence=0.9,
provider="test_provider",
processing_time=1.0,
audio_duration=2.0,
language="en-US"
)
fingerprint = await cache_manager.generate_audio_fingerprint(audio_data)
fingerprints.append(fingerprint)
# Cache with short TTL for some entries to create expired entries
ttl = 1 if i < 5 else 3600
await cache_manager.cache_transcription(fingerprint, result, ttl=ttl)
# Create frequent access pattern for some entries
if i >= 15: # Last 5 entries
for _ in range(10): # Access 10 times each
await cache_manager.get_cached_transcription(fingerprint)
# Wait for some entries to expire
await asyncio.sleep(1.1)
# Perform optimization
optimization_results = await cache_manager.optimize_cache_performance()
# Verify optimization results structure
assert "initial_stats" in optimization_results
assert "expired_evicted" in optimization_results
assert "optimizations_applied" in optimization_results
assert "final_stats" in optimization_results
# Verify expired entries were evicted
assert optimization_results["expired_evicted"] >= 5
# Verify optimizations were applied
optimizations = optimization_results["optimizations_applied"]
assert isinstance(optimizations, list)
# Check that frequently accessed entries were promoted
frequent_promotion = any("frequently accessed" in opt for opt in optimizations)
assert frequent_promotion
@pytest.mark.asyncio
async def test_identical_audio_produces_cache_hits(self, cache_manager):
"""
Test that identical audio data produces cache hits.
**Validates: Requirements 4.1, 4.3**
"""
async with cache_manager:
# Create identical audio data
audio_data = b"identical_audio_content" * 200
result1 = TranscriptionResult(
text="first transcription",
confidence=0.95,
provider="provider1",
processing_time=1.0,
audio_duration=2.0,
language="en-US"
)
# First transcription and caching
fingerprint1 = await cache_manager.generate_audio_fingerprint(audio_data)
await cache_manager.cache_transcription(fingerprint1, result1)
# Second identical audio should produce same fingerprint and cache hit
fingerprint2 = await cache_manager.generate_audio_fingerprint(audio_data)
assert fingerprint1 == fingerprint2
cached_result = await cache_manager.get_cached_transcription(fingerprint2)
assert cached_result is not None
assert cached_result.text == result1.text
assert cached_result.provider == result1.provider
@pytest.mark.asyncio
async def test_different_audio_produces_cache_misses(self, cache_manager):
"""
Test that different audio data produces cache misses.
**Validates: Requirements 4.5**
"""
async with cache_manager:
# Create different audio data
audio_data1 = b"first_audio_content" * 200
audio_data2 = b"second_audio_content" * 200
result1 = TranscriptionResult(
text="first transcription",
confidence=0.95,
provider="provider1",
processing_time=1.0,
audio_duration=2.0,
language="en-US"
)
# Cache first audio
fingerprint1 = await cache_manager.generate_audio_fingerprint(audio_data1)
await cache_manager.cache_transcription(fingerprint1, result1)
# Different audio should produce different fingerprint and cache miss
fingerprint2 = await cache_manager.generate_audio_fingerprint(audio_data2)
assert fingerprint1 != fingerprint2
cached_result = await cache_manager.get_cached_transcription(fingerprint2)
assert cached_result is None
@pytest.mark.asyncio
async def test_cache_performance_under_load(self, cache_manager):
"""
Test cache performance under concurrent load.
**Validates: Requirements 4.3**
"""
async with cache_manager:
import time
async def cache_operation(index):
"""Perform cache operations for a specific index."""
audio_data = f"load_test_audio_{index}".encode() * 100
result = TranscriptionResult(
text=f"load_test_transcription_{index}",
confidence=0.9,
provider="load_test_provider",
processing_time=0.5,
audio_duration=1.0,
language="en-US"
)
# Generate fingerprint
fingerprint = await cache_manager.generate_audio_fingerprint(audio_data)
# Cache miss
start_time = time.time()
cached_result = await cache_manager.get_cached_transcription(fingerprint)
miss_time = time.time() - start_time
assert cached_result is None
# Cache the result
await cache_manager.cache_transcription(fingerprint, result)
# Cache hit
start_time = time.time()
cached_result = await cache_manager.get_cached_transcription(fingerprint)
hit_time = time.time() - start_time
assert cached_result is not None
return miss_time, hit_time
# Run concurrent cache operations
tasks = [cache_operation(i) for i in range(20)]
results = await asyncio.gather(*tasks)
# Verify all operations completed successfully
assert len(results) == 20
# Cache hits should generally be faster than misses
miss_times = [r[0] for r in results]
hit_times = [r[1] for r in results]
avg_miss_time = sum(miss_times) / len(miss_times)
avg_hit_time = sum(hit_times) / len(hit_times)
# Cache hits should be faster (though this may not always be true in tests)
# The important thing is that both operations complete successfully
assert avg_miss_time >= 0
assert avg_hit_time >= 0
# Verify final statistics
stats = await cache_manager.get_cache_stats()
assert stats.total_requests >= 40 # At least 20 misses + 20 hits
assert stats.cache_hits >= 20
assert stats.cache_misses >= 20
@pytest.mark.asyncio
async def test_cache_size_limits_and_eviction(self, cache_manager):
"""
Test cache size limits and LRU eviction behavior.
**Validates: Requirements 4.2**
"""
# Create cache manager with very small size to force eviction
small_cache = CacheManager(max_size_mb=0.01, enable_stats=True) # 10KB only
async with small_cache:
cached_items = []
# Fill cache beyond capacity
for i in range(10):
audio_data = f"large_audio_data_{i}".encode() * 2000 # Make it large
result = TranscriptionResult(
text=f"large_transcription_{i}" * 100, # Make text large
confidence=0.9,
provider="test_provider",
processing_time=1.0,
audio_duration=1.0,
language="en-US"
)
fingerprint = await small_cache.generate_audio_fingerprint(audio_data)
await small_cache.cache_transcription(fingerprint, result)
cached_items.append((fingerprint, result))
# Access some items to make them recently used
for fingerprint, _ in cached_items[-3:]: # Access last 3 items
await small_cache.get_cached_transcription(fingerprint)
# Check that evictions occurred
stats = await small_cache.get_cache_stats()
assert stats.evictions > 0
# Recently accessed items should be more likely to remain
remaining_count = 0
for fingerprint, _ in cached_items[-3:]:
cached_result = await small_cache.get_cached_transcription(fingerprint)
if cached_result is not None:
remaining_count += 1
# At least some recently accessed items should remain
# (exact behavior depends on size calculations)
assert remaining_count >= 0 # Basic sanity check
@pytest.mark.asyncio
async def test_cache_ttl_expiration_behavior(self, cache_manager):
"""
Test TTL-based cache expiration and statistics.
**Validates: Requirements 4.4**
"""
async with cache_manager:
audio_data = b"ttl_test_audio" * 100
result = TranscriptionResult(
text="ttl test transcription",
confidence=0.95,
provider="ttl_test_provider",
processing_time=1.0,
audio_duration=2.0,
language="en-US"
)
fingerprint = await cache_manager.generate_audio_fingerprint(audio_data)
# Cache with short TTL
await cache_manager.cache_transcription(fingerprint, result, ttl=1)
# Should be available immediately
cached_result = await cache_manager.get_cached_transcription(fingerprint)
assert cached_result is not None
# Wait for expiration
await asyncio.sleep(1.1)
# Should now be expired (cache miss)
cached_result = await cache_manager.get_cached_transcription(fingerprint)
assert cached_result is None
# Check that expiration was tracked in statistics
stats = await cache_manager.get_cache_stats()
assert stats.cache_misses >= 1 # The expired access should count as miss eviction
small_cache = CacheManager(max_size_mb=0.01, enable_stats=True) # 10KB only
async with small_cache:
cached_items = []
# Fill cache beyond capacity
for i in range(10):
audio_data = f"large_audio_data_{i}".encode() * 2000 # Make it large
result = TranscriptionResult(
text=f"large_transcription_{i}" * 100, # Make text large
confidence=0.9,
provider="test_provider",
processing_time=1.0,
audio_duration=1.0,
language="en-US"
)
fingerprint = await small_cache.generate_audio_fingerprint(audio_data)
await small_cache.cache_transcription(fingerprint, result)
cached_items.append((fingerprint, result))
# Access some items to make them recently used
for fingerprint, _ in cached_items[-3:]: # Access last 3 items
await small_cache.get_cached_transcription(fingerprint)
# Check that evictions occurred
stats = await small_cache.get_cache_stats()
assert stats.evictions > 0
# Recently accessed items should be more likely to remain
remaining_count = 0
for fingerprint, _ in cached_items[-3:]:
cached_result = await small_cache.get_cached_transcription(fingerprint)
if cached_result is not None:
remaining_count += 1
# At least some recently accessed items should remain
# (exact behavior depends on size calculations)
assert remaining_count >= 0 # Basic sanity check
@pytest.mark.asyncio
async def test_cache_ttl_expiration_behavior(self, cache_manager):
"""
Test TTL-based cache expiration and statistics.
**Validates: Requirements 4.4**
"""
async with cache_manager:
audio_data = b"ttl_test_audio" * 100
result = TranscriptionResult(
text="ttl test transcription",
confidence=0.95,
provider="ttl_test_provider",
processing_time=1.0,
audio_duration=2.0,
language="en-US"
)
fingerprint = await cache_manager.generate_audio_fingerprint(audio_data)
# Cache with short TTL
await cache_manager.cache_transcription(fingerprint, result, ttl=1)
# Should be available immediately
cached_result = await cache_manager.get_cached_transcription(fingerprint)
assert cached_result is not None
# Wait for expiration
await asyncio.sleep(1.1)
# Should now be expired (cache miss)
cached_result = await cache_manager.get_cached_transcription(fingerprint)
assert cached_result is None
# Check that expiration was tracked in statistics
stats = await cache_manager.get_cache_stats()
assert stats.cache_misses >= 1 # The expired access should count as miss
if __name__ == "__main__":
pytest.main([__file__])
"""
Unit tests for the CacheManager implementation.
Tests cover audio fingerprinting, LRU cache behavior, TTL expiration,
cache statistics tracking, and cache hit optimization.
"""
import asyncio
import pytest
import time
from datetime import datetime
from unittest.mock import AsyncMock, MagicMock, patch
from voice_control.cache_manager import CacheManager, CacheEntry, create_cache_manager
from voice_control.models import TranscriptionResult, CacheStats
from voice_control.exceptions import CacheError
class TestCacheEntry:
"""Test the CacheEntry data class."""
def test_cache_entry_creation(self):
"""Test creating a cache entry."""
result = TranscriptionResult(
text="hello world",
confidence=0.95,
provider="test_provider",
processing_time=1.0,
audio_duration=2.0,
language="en-US"
)
entry = CacheEntry(
result=result,
created_at=time.time(),
last_accessed=time.time(),
ttl=3600
)
assert entry.result == result
assert entry.ttl == 3600
assert entry.access_count == 0
assert entry.size_bytes > 0
def test_cache_entry_expiration(self):
"""Test cache entry expiration logic."""
result = TranscriptionResult(
text="test",
confidence=0.9,
provider="test",
processing_time=1.0,
audio_duration=1.0,
language="en-US"
)
# Create expired entry
entry = CacheEntry(
result=result,
created_at=time.time() - 7200, # 2 hours ago
last_accessed=time.time() - 3600, # 1 hour ago
ttl=3600 # 1 hour TTL
)
assert entry.is_expired
def test_cache_entry_touch(self):
"""Test updating entry access information."""
result = TranscriptionResult(
text="test",
confidence=0.9,
provider="test",
processing_time=1.0,
audio_duration=1.0,
language="en-US"
)
entry = CacheEntry(
result=result,
created_at=time.time(),
last_accessed=time.time(),
ttl=3600
)
initial_access_count = entry.access_count
initial_last_accessed = entry.last_accessed
time.sleep(0.01) # Small delay
entry.touch()
assert entry.access_count == initial_access_count + 1
assert entry.last_accessed > initial_last_accessed
class TestCacheManager:
"""Test the CacheManager class."""
def cache_manager(self):
"""Create a cache manager for testing."""
return CacheManager(