-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathconftest.py
More file actions
368 lines (274 loc) · 9.23 KB
/
Copy pathconftest.py
File metadata and controls
368 lines (274 loc) · 9.23 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
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
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
"""Shared fixtures and utilities for SDK tests."""
from __future__ import annotations
import asyncio
import threading
from typing import Any, Dict
from dataclasses import field, dataclass
from unittest.mock import Mock, AsyncMock
import httpx
import pytest
from runloop_api_client import Runloop, AsyncRunloop
# Test ID constants
TEST_IDS = {
"devbox": "dev_123",
"execution": "exec_123",
"snapshot": "snap_123",
"blueprint": "bp_123",
"object": "obj_123",
"scorer": "scorer_123",
"agent": "agent_123",
}
# Test URL constants
TEST_URLS = {
"upload": "https://upload.example.com/obj_123",
"download": "https://download.example.com/obj_123",
}
# Timing constants for thread/task synchronization tests
THREAD_STARTUP_DELAY = 0.1 # Time to allow threads/tasks to start
TASK_COMPLETION_SHORT = 0.02 # Brief async operation
TASK_COMPLETION_LONG = 1.0 # Long-running operation for cancellation tests
NUM_CONCURRENT_THREADS = 5 # Number of threads for concurrency tests
# Mock data structures using dataclasses for type safety
@dataclass
class MockDevboxView:
"""Mock DevboxView for testing."""
id: str = "dev_123"
status: str = "running"
name: str = "test-devbox"
@dataclass
class MockExecutionView:
"""Mock DevboxAsyncExecutionDetailView for testing."""
execution_id: str = "exec_123"
devbox_id: str = "dev_123"
status: str = "completed"
exit_status: int = 0
stdout: str = "output"
stderr: str = ""
stdout_truncated: bool = False
stderr_truncated: bool = False
@dataclass
class MockSnapshotView:
"""Mock DevboxSnapshotView for testing."""
id: str = "snap_123"
status: str = "completed"
name: str = "test-snapshot"
@dataclass
class MockBlueprintView:
"""Mock BlueprintView for testing."""
id: str = "bp_123"
status: str = "built"
name: str = "test-blueprint"
@dataclass
class MockObjectView:
"""Mock ObjectView for testing."""
id: str = "obj_123"
upload_url: str = "https://upload.example.com/obj_123"
name: str = "test-object"
@dataclass
class MockScorerView:
"""Mock ScorerView for testing."""
id: str = "scorer_123"
bash_script: str = "echo 'score=1.0'"
type: str = "test_scorer"
@dataclass
class MockAgentView:
"""Mock AgentView for testing."""
id: str = "agent_123"
name: str = "test-agent"
create_time_ms: int = 1234567890000
is_public: bool = False
source: Any = None
@dataclass
class MockScenarioView:
"""Mock ScenarioView for testing."""
id: str = "scn_123"
name: str = "test-scenario"
metadata: Dict[str, str] = field(default_factory=dict)
@dataclass
class MockScenarioRunView:
"""Mock ScenarioRunView for testing."""
id: str = "run_123"
devbox_id: str = "dev_123"
scenario_id: str = "scn_123"
state: str = "running"
metadata: Dict[str, str] = field(default_factory=dict)
scoring_contract_result: object = None
@dataclass
class MockBenchmarkRunView:
"""Mock BenchmarkRunView for testing."""
id: str = "bench_run_123"
benchmark_id: str = "bench_123"
state: str = "running"
metadata: Dict[str, str] = field(default_factory=dict)
start_time_ms: int = 1234567890000
duration_ms: int | None = None
score: float | None = None
class AsyncIterableMock:
"""A simple async iterable mock for testing paginated responses."""
def __init__(self, items: list[Any]) -> None:
self._items = items
async def __aiter__(self):
for item in self._items:
yield item
def create_mock_httpx_client(methods: dict[str, Any] | None = None) -> AsyncMock:
"""
Create a mock httpx.AsyncClient with proper context manager setup.
Args:
methods: Optional dict of method names to AsyncMock return values.
Common keys: 'get', 'put'
Returns:
Configured AsyncMock for httpx.AsyncClient
Note: We don't use spec here because we need to manually set context manager
methods which are not allowed with spec.
"""
mock_client = AsyncMock()
mock_client.__aenter__ = AsyncMock(return_value=mock_client)
mock_client.__aexit__ = AsyncMock(return_value=None)
if methods:
for method_name, return_value in methods.items():
setattr(mock_client, method_name, AsyncMock(return_value=return_value))
return mock_client
def create_mock_httpx_response(**attrs: Any) -> Mock:
"""
Create a mock httpx.Response with specified attributes.
Args:
**attrs: Attributes to set on the mock response.
Common: content, text, encoding
Returns:
Mock configured with httpx.Response spec and attributes
"""
mock_response = Mock(spec=httpx.Response)
for key, value in attrs.items():
setattr(mock_response, key, value)
return mock_response
@pytest.fixture
def mock_client() -> Mock:
"""Create a mock Runloop client."""
return Mock(spec=Runloop)
@pytest.fixture
def mock_async_client() -> AsyncMock:
"""Create a mock AsyncRunloop client."""
return AsyncMock(spec=AsyncRunloop)
@pytest.fixture
def devbox_view() -> MockDevboxView:
"""Create a mock DevboxView."""
return MockDevboxView()
@pytest.fixture
def execution_view() -> MockExecutionView:
"""Create a mock DevboxAsyncExecutionDetailView."""
return MockExecutionView()
@pytest.fixture
def snapshot_view() -> MockSnapshotView:
"""Create a mock DevboxSnapshotView."""
return MockSnapshotView()
@pytest.fixture
def blueprint_view() -> MockBlueprintView:
"""Create a mock BlueprintView."""
return MockBlueprintView()
@pytest.fixture
def object_view() -> MockObjectView:
"""Create a mock ObjectView."""
return MockObjectView()
@pytest.fixture
def scorer_view() -> MockScorerView:
"""Create a mock ScorerView."""
return MockScorerView()
@pytest.fixture
def agent_view() -> MockAgentView:
"""Create a mock AgentView."""
return MockAgentView()
@pytest.fixture
def scenario_view() -> MockScenarioView:
"""Create a mock ScenarioView."""
return MockScenarioView()
@pytest.fixture
def scenario_run_view() -> MockScenarioRunView:
"""Create a mock ScenarioRunView."""
return MockScenarioRunView()
@pytest.fixture
def benchmark_run_view() -> MockBenchmarkRunView:
"""Create a mock BenchmarkRunView."""
return MockBenchmarkRunView()
@pytest.fixture
def mock_httpx_response() -> Mock:
"""Create a mock httpx.Response."""
response = Mock(spec=httpx.Response)
response.status_code = 200
response.content = b"test content"
response.text = "test content"
response.encoding = "utf-8"
response.raise_for_status = Mock()
return response
@pytest.fixture
def mock_stream() -> Mock:
"""Create a mock Stream for testing.
Note: We don't use spec here because we need to manually set context manager
and iterator methods which are not allowed with spec.
"""
stream = Mock()
stream.__iter__ = Mock(return_value=iter([]))
stream.__enter__ = Mock(return_value=stream)
stream.__exit__ = Mock(return_value=None)
stream.close = Mock()
return stream
@pytest.fixture
def mock_async_stream() -> AsyncMock:
"""Create a mock AsyncStream for testing.
Note: We don't use spec here because we need to manually set context manager
and async iterator methods which are not allowed with spec.
"""
async def async_iter():
return
yield # Make this a generator
stream = AsyncMock()
stream.__aiter__ = Mock(return_value=async_iter())
stream.__aenter__ = AsyncMock(return_value=stream)
stream.__aexit__ = AsyncMock(return_value=None)
stream.close = AsyncMock()
return stream
@pytest.fixture
async def async_task_cleanup():
"""
Fixture to ensure async tasks are properly cleaned up after tests.
Usage:
async def test_something(async_task_cleanup):
task = asyncio.create_task(some_coroutine())
async_task_cleanup.append(task)
# Task will be automatically cancelled and awaited on teardown
Yields:
List to append tasks to for automatic cleanup
"""
tasks: list[asyncio.Task[Any]] = []
yield tasks
# Cleanup: cancel all tasks and wait for them to finish
for task in tasks:
if not task.done():
task.cancel()
try:
await task
except asyncio.CancelledError:
pass
@pytest.fixture
def thread_cleanup():
"""
Fixture to ensure threads are properly cleaned up after tests.
Usage:
def test_something(thread_cleanup):
threads, stop_events = thread_cleanup
stop_event = threading.Event()
thread = threading.Thread(target=worker, args=(stop_event,))
thread.start()
threads.append(thread)
stop_events.append(stop_event)
# Thread will be automatically stopped and joined on teardown
Yields:
Tuple of (threads list, stop_events list) for automatic cleanup
"""
threads: list[threading.Thread] = []
stop_events: list[threading.Event] = []
yield threads, stop_events
# Cleanup: signal all threads to stop and wait for them
for event in stop_events:
event.set()
for thread in threads:
thread.join(timeout=2.0)