-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathconftest.py
More file actions
432 lines (397 loc) · 17.2 KB
/
Copy pathconftest.py
File metadata and controls
432 lines (397 loc) · 17.2 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
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
from __future__ import annotations
from collections.abc import Callable, Iterator
from pathlib import Path
import sys
from typing import Any
import pytest
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
from vesper.config import Settings
from vesper.rpc import CiderRpcClient
from vesper.resolver import FallbackResolver, ResolvedAction, SessionQueryPlan, SessionSearchSource
from vesper.service import CiderAgentService
from vesper.storage import PreferenceStore, close_connections, close_lifecycle_locks
class FakeResponse:
def __init__(self, status_code: int, payload: Any = None) -> None:
self.status_code = status_code
self._payload = payload
@property
def is_error(self) -> bool:
return self.status_code >= 400
def json(self) -> Any:
if isinstance(self._payload, Exception):
raise self._payload
return self._payload
class FakeSession:
def __init__(self, responder: Callable[[str, str, dict[str, str], Any], FakeResponse]) -> None:
self._responder = responder
self.requests: list[dict[str, Any]] = []
def request(self, method: str, path: str, headers: dict[str, str], json: Any = None) -> FakeResponse:
self.requests.append({"method": method, "path": path, "headers": headers, "json": json})
return self._responder(method, path, headers, json)
def close(self) -> None:
return None
class StubRpcClient:
def __init__(self) -> None:
self.is_playing = True
self.volume = 0.5
self.current_track: dict[str, Any] | None = self._track(
"track-1",
"Track",
"Artist",
"Album",
is_library=True,
)
self.queue_items = [self._track("queued-track", "Queued", "Queued Artist", "Queued Album")]
self.posts: list[dict[str, Any]] = []
self.playback_get_calls: list[str] = []
self.search_catalog_calls: list[dict[str, Any]] = []
def _track(
self,
track_id: str,
title: str,
artist: str = "Artist",
album: str = "Album",
*,
is_library: bool = False,
) -> dict[str, Any]:
return {
"id": track_id,
"type": "songs",
"attributes": {
"name": title,
"artistName": artist,
"albumName": album,
"playParams": {"id": track_id, "kind": "songs", "isLibrary": is_library},
"durationInMillis": 180000,
},
}
def close(self) -> None:
return None
def set_failure_callback(self, callback) -> None:
return None
def playback_get(self, path: str):
self.playback_get_calls.append(path)
if path == "/now-playing":
return {"info": self.current_track["attributes"] if self.current_track is not None else {}}
if path == "/queue":
return self.queue_items
if path == "/is-playing":
return {"status": "ok", "is_playing": self.is_playing}
if path == "/volume":
return {"volume": self.volume}
if path == "/repeat-mode":
return {"value": 0}
if path == "/shuffle-mode":
return {"value": 0}
if path == "/autoplay":
return {"value": False}
return {"value": True}
def playback_post(self, path: str, body=None):
self.posts.append({"path": path, "body": body})
if path == "/pause":
self.is_playing = False
elif path == "/play":
self.is_playing = True
elif path == "/stop":
self.is_playing = False
elif path == "/next":
self.is_playing = False
self.current_track = None
elif path == "/volume" and isinstance(body, dict):
self.volume = body.get("volume", self.volume)
elif path == "/play-item" and isinstance(body, dict):
item_id = str(body.get("id", "")).strip()
self.current_track = self._catalog_track_for_id(item_id)
self.is_playing = True
elif path == "/queue/clear-queue":
self.queue_items = []
return {"path": path, "body": body}
def _catalog_track_for_id(self, item_id: str) -> dict[str, Any]:
catalog_map = {
"catalog-track-favorite": self._track("catalog-track-favorite", "Liked Song", "Favorite Artist"),
"catalog-track-2": self._track("catalog-track-2", "Another Song", "Favorite Artist"),
"catalog-track-3": self._track("catalog-track-3", "Third Song", "Favorite Artist"),
"catalog-track-1": self._track("catalog-track-1", "k-pop", "Catalog Artist"),
}
return catalog_map.get(item_id, self._track(item_id or "unknown-track", item_id or "Unknown"))
def search_catalog(self, query: str, *, limit: int = 10, storefront: str = "us", offset: int = 0):
self.search_catalog_calls.append({"query": query, "limit": limit, "storefront": storefront, "offset": offset})
if query == "Favorite Artist Liked Song":
return {
"data": {
"results": {
"songs": {
"data": [
{
"id": "catalog-track-favorite",
"type": "songs",
"attributes": {
"name": "Liked Song",
"artistName": "Favorite Artist",
"playParams": {"id": "catalog-track-favorite", "kind": "songs", "isLibrary": False},
},
}
]
}
}
}
}
if query == "Favorite Artist Another Song":
return {
"data": {
"results": {
"songs": {
"data": [
{
"id": "catalog-track-2",
"type": "songs",
"attributes": {
"name": "Another Song",
"artistName": "Favorite Artist",
"albumName": "Album",
"playParams": {"id": "catalog-track-2", "kind": "songs", "isLibrary": False},
},
}
]
}
}
}
}
if query == "Favorite Artist Third Song":
return {
"data": {
"results": {
"songs": {
"data": [
{
"id": "catalog-track-3",
"type": "songs",
"attributes": {
"name": "Third Song",
"artistName": "Favorite Artist",
"albumName": "Album",
"playParams": {"id": "catalog-track-3", "kind": "songs", "isLibrary": False},
},
}
]
}
}
}
}
if query == "Favorite Artist Wide Pool":
return {
"data": {
"results": {
"songs": {
"data": [
{
"id": f"catalog-wide-{index}",
"type": "songs",
"attributes": {
"name": f"Wide Song {index}",
"artistName": "Favorite Artist",
"albumName": "Album",
"playParams": {"id": f"catalog-wide-{index}", "kind": "songs", "isLibrary": False},
},
}
for index in range(1, 9)
]
}
}
}
}
return {
"data": {
"results": {
"songs": {
"data": [
{
"id": "catalog-track-1",
"type": "songs",
"attributes": {
"name": query,
"artistName": "Catalog Artist",
"playParams": {"id": "catalog-track-1", "kind": "songs", "isLibrary": False},
},
}
]
}
}
}
}
def search_library(self, query: str, *, limit: int = 10, types: list[str] | None = None):
return {
"data": {
"results": {
"library-songs": {
"data": [
{
"id": "library-track-1",
"type": "library-songs",
"attributes": {
"name": query,
"artistName": "Library Artist",
"playParams": {"id": "library-track-1", "kind": "songs", "isLibrary": True},
},
}
]
},
"library-playlists": {"data": [{"id": "playlist-1", "type": "library-playlists", "attributes": {"name": "Mix"}}]},
"library-albums": {"data": [{"id": "album-1", "type": "library-albums", "attributes": {"name": "Album"}}]},
"library-artists": {"data": [{"id": "artist-1", "type": "library-artists", "attributes": {"name": "Artist"}}]},
}
}
}
def run_amapi_v3(self, path: str, *, method: str = "GET", body: dict[str, Any] | None = None):
if path.startswith("/v1/me/library/search?") and "library-songs" in path:
return {
"data": {
"results": {
"library-songs": {
"data": [
{
"id": "library-track-1",
"type": "library-songs",
"attributes": {
"name": "Liked Song",
"artistName": "Favorite Artist",
"playParams": {"id": "library-track-1", "kind": "songs", "isLibrary": True},
},
}
]
}
}
}
}
if path.startswith("/v1/me/library/playlists?"):
return {
"data": {
"data": [
{"id": "playlist-1", "type": "library-playlists", "attributes": {"name": "Mix"}},
]
}
}
if "/tracks?limit=" in path:
return {
"data": {
"data": [
{
"id": "track-1",
"type": "library-songs",
"attributes": {
"name": "Playlist Track",
"artistName": "Artist",
"playParams": {"id": "track-1", "kind": "songs", "isLibrary": True},
},
}
]
}
}
if path.startswith("/v1/me/recent/played/tracks"):
return {"data": {"data": [{"id": "recent-1", "type": "library-songs", "attributes": {"name": "Recent"}}]}}
return {"data": {"data": [{"id": "playlist-1", "type": "library-playlists", "attributes": {"name": "Mix"}}]}}
class StubResolver(FallbackResolver):
def __init__(self) -> None:
self.session_plan_calls = 0
def resolve(self, text: str, service: Any) -> ResolvedAction:
normalized = text.strip().lower()
if "kep1er" in normalized:
return ResolvedAction(action="search", parameters={"query": "kep1er", "limit": 3, "storefront": "us"}, resolver="stub")
if "pink" in normalized:
return ResolvedAction(
action="play_candidate_match",
parameters={
"candidate_tracks": [{"title": "Just Give Me a Reason", "artist": "P!nk"}],
"candidate_artists": ["P!nk"],
"candidate_queries": ["Pink"],
},
resolver="stub",
)
if "list playlists" in normalized or "what playlists" in normalized:
return ResolvedAction(action="list_library_playlists", parameters={}, resolver="stub")
if "play playlist" in normalized:
return ResolvedAction(action="play_library_playlist", parameters={"playlist_name": text.split("play playlist", 1)[-1].strip()}, resolver="stub")
if "i like this track" in normalized or "i like this song" in normalized:
return ResolvedAction(action="like_current_track", parameters={}, resolver="stub")
if normalized in {"play some music", "play music", "play something"}:
return ResolvedAction(action="play_session", parameters={"request": text}, resolver="stub")
if "upbeat" in normalized or "morning" in normalized:
return ResolvedAction(action="play_session", parameters={"request": text}, resolver="stub")
if "more pop" in normalized:
return ResolvedAction(action="steer_session", parameters={"request": text}, resolver="stub")
return ResolvedAction(action="status", parameters={}, resolver="stub")
def plan_session(self, request: str, service: Any, session: dict[str, Any], count: int):
self.session_plan_calls += 1
if request.strip().casefold() in {"play some music", "play music", "play something"}:
return SessionQueryPlan(
search_sources=[SessionSearchSource(kind="preference", term="__preference_seeded__")],
resolver="stub",
)
if self.session_plan_calls == 1:
query = "Favorite Artist Liked Song"
elif self.session_plan_calls == 2:
query = "Favorite Artist Another Song"
elif self.session_plan_calls == 3:
query = "Favorite Artist Third Song"
else:
query = "k-pop"
return type(
"Plan",
(),
{
"search_queries": [query],
"resolver": "stub",
"raw": None,
"reasoning": None,
"raw_content": None,
},
)()
@pytest.fixture
def settings(tmp_path: Path) -> Settings:
return Settings(
http_host="127.0.0.1",
http_port=8766,
public_base_url="http://127.0.0.1:8766",
cider_base_url="http://localhost:10767",
cider_api_token="secret-token",
default_search_source="catalog",
resolver_backend="fallback",
resolver_base_url="https://api.openai.com/v1",
resolver_model=None,
resolver_api_key=None,
resolver_include_reasoning=False,
resolver_include_raw_output=False,
request_timeout_seconds=10.0,
verify_tls=True,
log_level="INFO",
database_path=tmp_path / "vesper.db",
config_path=None,
)
@pytest.fixture
def service(settings: Settings) -> Iterator[CiderAgentService]:
svc = CiderAgentService(
settings,
rpc_client=StubRpcClient(),
preference_store=PreferenceStore(settings.database_path),
resolver=StubResolver(),
)
yield svc
# Shut down the reused playback snapshot thread pool (issue #67) so its
# worker threads don't accumulate across the many tests using this fixture.
# The full service.close() is exercised by the dedicated teardown tests.
svc._playback_ctrl.close()
@pytest.fixture
def rpc_client(settings: Settings):
session = FakeSession(lambda method, path, headers, body: FakeResponse(200, {"ok": True}))
return CiderRpcClient(settings, session=session), session
@pytest.fixture(autouse=True)
def _close_storage_connections() -> Any:
"""Release cached SQLite connections after each test.
Each test uses a fresh ``tmp_path`` database. The thread-local connection
cache (issue #50) would otherwise hold a connection to the stale file
across tests, leaking file handles. Tearing connections down here keeps the
cache per-test.
"""
yield
close_connections()
close_lifecycle_locks()