-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathconftest.py
More file actions
212 lines (153 loc) · 8.19 KB
/
Copy pathconftest.py
File metadata and controls
212 lines (153 loc) · 8.19 KB
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
"""
conftest.py — Pytest configuration and fixtures for Vision tests
================================================================
Shared fixtures for async tests, mocks, and integration setup.
"""
import asyncio
import json
import tempfile
from collections.abc import Generator
from pathlib import Path
from typing import Any
import pytest
# ──────────────────────────────────────────────────────────────────────────────
# Event Loop Management
# ──────────────────────────────────────────────────────────────────────────────
@pytest.fixture
def event_loop() -> Generator[asyncio.AbstractEventLoop, None, None]:
"""Create event loop for async tests."""
loop = asyncio.new_event_loop()
yield loop
loop.close()
# ──────────────────────────────────────────────────────────────────────────────
# Temporary Fixtures
# ──────────────────────────────────────────────────────────────────────────────
@pytest.fixture
def tmp_project_dir() -> Generator[Path, None, None]:
"""Create temporary project directory."""
with tempfile.TemporaryDirectory() as tmpdir:
yield Path(tmpdir)
@pytest.fixture
def tmp_config_file(tmp_project_dir: Path) -> Path:
"""Create temporary config file."""
config_file = tmp_project_dir / "config.json"
config_file.write_text("{}")
return config_file
# ──────────────────────────────────────────────────────────────────────────────
# Mock Fixtures
# ──────────────────────────────────────────────────────────────────────────────
@pytest.fixture
def mock_http_client():
"""Mock HTTP client for testing."""
class MockResponse:
def __init__(self, status_code: int = 200, text: str = "{}") -> None:
self.status_code = status_code
self.text = text
async def json(self) -> Any:
return json.loads(self.text)
class MockClient:
async def get(self, url: str, **kwargs: Any) -> MockResponse:
return MockResponse()
async def post(self, url: str, **kwargs: Any) -> MockResponse:
return MockResponse()
return MockClient()
@pytest.fixture
def mock_llm_response():
"""Mock LLM streaming response."""
class MockChoice:
def __init__(self):
self.delta = type(
"obj",
(object,),
{
"content": "Test response",
"tool_calls": None,
},
)()
self.finish_reason = "stop"
class MockStreamChunk:
def __init__(self):
self.choices = [MockChoice()]
async def mock_stream():
yield MockStreamChunk()
yield MockStreamChunk()
return mock_stream()
# ──────────────────────────────────────────────────────────────────────────────
# Logging Fixtures
# ──────────────────────────────────────────────────────────────────────────────
@pytest.fixture
def caplog_with_json(caplog):
"""Capture and parse JSON logs."""
class JsonLogCapture:
def __init__(self, caplog):
self.caplog = caplog
def get_records(self) -> list:
"""Parse captured log records."""
records = []
for record in self.caplog.records:
records.append(
{
"level": record.levelname,
"message": record.getMessage(),
}
)
return records
return JsonLogCapture(caplog)
# ──────────────────────────────────────────────────────────────────────────────
# Integration Fixtures
# ──────────────────────────────────────────────────────────────────────────────
@pytest.fixture
async def elite_metrics_clean():
"""Fresh metrics collector for each test."""
from elite_metrics import MetricsCollector
return MetricsCollector()
@pytest.fixture
async def elite_tool_executor_clean():
"""Fresh tool executor for each test."""
from elite_tools import SafeToolExecutor, ToolCache
return SafeToolExecutor(cache=ToolCache())
@pytest.fixture
def monkeypatch_env(monkeypatch):
"""Monkeypatch environment variables."""
def patch_env(key: str, value: str):
monkeypatch.setenv(key, value)
return patch_env
# ──────────────────────────────────────────────────────────────────────────────
# Marker-based Fixtures
# ──────────────────────────────────────────────────────────────────────────────
@pytest.fixture
def slow_test_warning(request):
"""Warn if slow tests run in quick test suite."""
if "slow" in request.keywords:
print("\n[SLOW TEST] This test may take several seconds - conftest.py:158")
# ──────────────────────────────────────────────────────────────────────────────
# Performance Monitoring
# ──────────────────────────────────────────────────────────────────────────────
@pytest.fixture
def benchmark_async():
"""Benchmark async function performance."""
import time
class AsyncBenchmark:
async def __call__(self, fn, *args, **kwargs):
start = time.monotonic()
result = await fn(*args, **kwargs)
elapsed = time.monotonic() - start
return {
"result": result,
"elapsed_ms": elapsed * 1000,
}
return AsyncBenchmark()
# ──────────────────────────────────────────────────────────────────────────────
# Cleanup & Teardown
# ──────────────────────────────────────────────────────────────────────────────
@pytest.fixture(autouse=True)
def cleanup_tasks():
"""Cancel any dangling async tasks after each test."""
yield
try:
loop = asyncio.get_running_loop()
except RuntimeError:
return # no running loop — nothing to cancel
pending = {t for t in asyncio.all_tasks(loop) if not t.done()}
for task in pending:
task.cancel()