File size: 8,394 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
"""
Pytest configuration and fixtures for voice control tests.

This module provides common fixtures and configuration for all tests
in the voice control optimization system.
"""

import pytest
import asyncio
import tempfile
import os
from typing import Dict, Any
from unittest.mock import Mock, AsyncMock
from datetime import datetime, timedelta

from hypothesis import settings, Verbosity
from hypothesis.strategies import composite, integers, floats, text, booleans, lists, dictionaries

from voice_control.models import (
    ProviderConfig, ProviderType, TranscriptionResult, UsageStats,
    ProviderStatus, ProcessedAudio, QuotaStatus, QuotaType
)
from voice_control.interfaces import STTProvider


# Configure Hypothesis for property-based testing
settings.register_profile("default", max_examples=100, verbosity=Verbosity.normal)
settings.register_profile("ci", max_examples=1000, verbosity=Verbosity.verbose)
settings.register_profile("dev", max_examples=10, verbosity=Verbosity.verbose)

# Use CI profile in CI environment, dev profile for local development
profile = os.environ.get("HYPOTHESIS_PROFILE", "default")
settings.load_profile(profile)


@pytest.fixture(scope="session")
def event_loop():
    """Create an instance of the default event loop for the test session."""
    loop = asyncio.get_event_loop_policy().new_event_loop()
    yield loop
    loop.close()


@pytest.fixture
def temp_dir():
    """Create a temporary directory for test files."""
    with tempfile.TemporaryDirectory() as tmpdir:
        yield tmpdir


@pytest.fixture
def sample_audio_data():
    """Generate sample audio data for testing."""
    # Generate 1 second of silence at 44.1kHz, 16-bit, mono
    import numpy as np
    sample_rate = 44100
    duration = 1.0
    samples = int(sample_rate * duration)
    audio_array = np.zeros(samples, dtype=np.int16)
    return audio_array.tobytes()


@pytest.fixture
def sample_provider_config():
    """Create a sample provider configuration for testing."""
    return ProviderConfig(
        name="test_provider",
        provider_type=ProviderType.WEB_SPEECH_API,
        enabled=True,
        priority=1,
        free_tier_limits={"requests_per_day": 1000, "audio_minutes_per_month": 60},
        rate_limits={"requests_per_minute": 10, "audio_minutes_per_hour": 5},
        supported_formats=["webm", "wav", "mp3"],
        supported_languages=["en-US", "en-GB"],
        cost_per_minute=0.0,
        api_credentials={"api_key": "test_key"},
        timeout_seconds=30,
        max_retries=3
    )


@pytest.fixture
def sample_transcription_result():
    """Create a sample transcription result for testing."""
    return TranscriptionResult(
        text="Hello world",
        confidence=0.95,
        provider="test_provider",
        processing_time=1.5,
        audio_duration=2.0,
        language="en-US",
        alternatives=["Hello world", "Hello word"],
        is_final=True,
        session_id="test_session_123"
    )


@pytest.fixture
def sample_usage_stats():
    """Create sample usage statistics for testing."""
    now = datetime.utcnow()
    return UsageStats(
        provider="test_provider",
        requests_count=100,
        audio_minutes=50.5,
        estimated_cost=2.50,
        success_rate=0.98,
        average_latency=1.2,
        time_window="hour",
        window_start=now - timedelta(hours=1),
        window_end=now
    )


@pytest.fixture
def sample_provider_status():
    """Create sample provider status for testing."""
    return ProviderStatus(
        name="test_provider",
        available=True,
        current_load=0.3,
        quota_remaining={"requests": 900.0, "audio_minutes": 45.5},
        last_error=None,
        response_time_avg=1.1,
        circuit_breaker_state="CLOSED",
        consecutive_failures=0
    )


@pytest.fixture
def mock_stt_provider(sample_provider_config, sample_transcription_result):
    """Create a mock STT provider for testing."""
    
    class MockSTTProvider(STTProvider):
        def __init__(self, config: ProviderConfig):
            super().__init__(config)
            self.health_status = True
            self.quota_status = {
                "requests_per_minute": QuotaStatus(
                    provider=config.name,
                    quota_type=QuotaType.REQUESTS_PER_MINUTE,
                    current_usage=5,
                    limit=10,
                    remaining=5,
                    reset_time=datetime.utcnow() + timedelta(minutes=1),
                    percentage_used=0.5
                )
            }
        
        async def transcribe_audio(self, audio_data: bytes, format: str, language: str = "en-US", **kwargs):
            return sample_transcription_result
        
        async def transcribe_streaming(self, audio_stream, format: str, language: str = "en-US", **kwargs):
            async for chunk in audio_stream:
                yield sample_transcription_result
        
        async def check_health(self) -> bool:
            return self.health_status
        
        async def get_quota_status(self):
            return self.quota_status
        
        def supports_format(self, format: str) -> bool:
            return format in self.config.supported_formats
        
        def supports_language(self, language: str) -> bool:
            return language in self.config.supported_languages
        
        async def estimate_cost(self, audio_duration: float) -> float:
            return audio_duration * self.config.cost_per_minute / 60.0
    
    return MockSTTProvider(sample_provider_config)


# Hypothesis strategies for generating test data
@composite
def provider_config_strategy(draw):
    """Strategy for generating valid ProviderConfig instances."""
    return ProviderConfig(
        name=draw(text(min_size=1, max_size=50)),
        provider_type=draw(integers(min_value=0, max_value=4).map(lambda x: list(ProviderType)[x])),
        enabled=draw(booleans()),
        priority=draw(integers(min_value=0, max_value=100)),
        free_tier_limits=draw(dictionaries(text(), integers(min_value=0))),
        rate_limits=draw(dictionaries(text(), integers(min_value=1))),
        supported_formats=draw(lists(text(min_size=1), min_size=1)),
        supported_languages=draw(lists(text(min_size=2, max_size=5), min_size=1)),
        cost_per_minute=draw(floats(min_value=0.0, max_value=1.0)),
        api_credentials=draw(dictionaries(text(), text())),
        timeout_seconds=draw(integers(min_value=1, max_value=300)),
        max_retries=draw(integers(min_value=0, max_value=10))
    )


@composite
def transcription_result_strategy(draw):
    """Strategy for generating valid TranscriptionResult instances."""
    return TranscriptionResult(
        text=draw(text()),
        confidence=draw(floats(min_value=0.0, max_value=1.0)),
        provider=draw(text(min_size=1)),
        processing_time=draw(floats(min_value=0.0, max_value=60.0)),
        audio_duration=draw(floats(min_value=0.1, max_value=3600.0)),
        language=draw(text(min_size=2, max_size=10)),
        alternatives=draw(lists(text(), max_size=5)),
        is_final=draw(booleans())
    )


@composite
def audio_data_strategy(draw):
    """Strategy for generating audio data bytes."""
    size = draw(integers(min_value=1024, max_value=1024*1024))  # 1KB to 1MB
    return bytes(draw(integers(min_value=0, max_value=255)) for _ in range(size))


@composite
def quota_status_strategy(draw):
    """Strategy for generating valid QuotaStatus instances."""
    limit = draw(floats(min_value=1.0, max_value=10000.0))
    current_usage = draw(floats(min_value=0.0, max_value=limit * 1.1))  # Allow slight over-usage
    
    return QuotaStatus(
        provider=draw(text(min_size=1)),
        quota_type=draw(integers(min_value=0, max_value=4).map(lambda x: list(QuotaType)[x])),
        current_usage=current_usage,
        limit=limit,
        remaining=max(0, limit - current_usage),
        reset_time=datetime.utcnow() + timedelta(hours=draw(integers(min_value=1, max_value=24))),
        percentage_used=min(current_usage / limit, 1.0) if limit > 0 else 0.0
    )


# Test data constants
VALID_AUDIO_FORMATS = ["webm", "wav", "mp3", "ogg", "flac"]
VALID_LANGUAGES = ["en-US", "en-GB", "es-ES", "fr-FR", "de-DE", "ja-JP", "zh-CN"]
PROVIDER_NAMES = ["web_speech_api", "google_speech", "azure_speech", "assembly_ai", "deepgram"]