forked from github/copilot-sdk
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_session_fs.py
More file actions
306 lines (248 loc) · 9.93 KB
/
Copy pathtest_session_fs.py
File metadata and controls
306 lines (248 loc) · 9.93 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
"""E2E tests for SessionFs virtual filesystem support."""
from __future__ import annotations
import os
import re
import shutil
import tempfile
from pathlib import Path
from typing import Any
import pytest
import pytest_asyncio
from copilot import CopilotClient, SessionFsConfig, SessionFsHandler
from copilot.client import SubprocessConfig
from copilot.session import CopilotSession, PermissionHandler
from .testharness import E2ETestContext
pytestmark = pytest.mark.asyncio(loop_scope="module")
class InMemoryFS:
"""Simple in memory filesystem for testing."""
def __init__(self):
self._files: dict[str, str] = {}
self._dirs: set[str] = {"/"}
def _ensure_parents(self, path: str) -> None:
parts = path.split("/")
for i in range(1, len(parts) - 1):
self._dirs.add("/".join(parts[: i + 1]))
def read_file(self, path: str) -> str:
if path not in self._files:
raise FileNotFoundError(f"File not found: {path}")
return self._files[path]
def write_file(self, path: str, content: str) -> None:
self._ensure_parents(path)
self._files[path] = content
def append_file(self, path: str, content: str) -> None:
self._ensure_parents(path)
self._files[path] = self._files.get(path, "") + content
def exists(self, path: str) -> bool:
p = path.rstrip("/") or "/"
return p in self._files or p in self._dirs
def mkdir(self, path: str, recursive: bool = False) -> None:
if recursive:
self._ensure_parents(path + "/x")
self._dirs.add(path.rstrip("/"))
def readdir(self, path: str) -> list[str]:
prefix = path if path.endswith("/") else path + "/"
entries: set[str] = set()
for key in list(self._files.keys()) + list(self._dirs):
if key.startswith(prefix) and len(key) > len(prefix):
rest = key[len(prefix) :]
slash = rest.find("/")
entries.add(rest[:slash] if slash >= 0 else rest)
return sorted(entries)
def remove(self, path: str) -> None:
p = path.rstrip("/") or "/"
self._files.pop(p, None)
self._dirs.discard(p)
def rename(self, src: str, dest: str) -> None:
if src in self._files:
self._ensure_parents(dest)
self._files[dest] = self._files.pop(src)
class InMemorySessionFsHandler(SessionFsHandler):
"""SessionFs handler backed by an in memory filesystem."""
def __init__(self, session_id: str, fs: InMemoryFS):
self._session_id = session_id
self._fs = fs
def _sp(self, path: str) -> str:
if path.startswith("/"):
return f"/{self._session_id}{path}"
return f"/{self._session_id}/{path}"
async def read_file(self, *, session_id: str, path: str) -> dict[str, Any]:
return {"content": self._fs.read_file(self._sp(path))}
async def write_file(
self, *, session_id: str, path: str, content: str, mode: int | None = None
) -> None:
self._fs.write_file(self._sp(path), content)
async def append_file(
self, *, session_id: str, path: str, content: str, mode: int | None = None
) -> None:
self._fs.append_file(self._sp(path), content)
async def exists(self, *, session_id: str, path: str) -> dict[str, Any]:
return {"exists": self._fs.exists(self._sp(path))}
async def stat(self, *, session_id: str, path: str) -> dict[str, Any]:
p = self._sp(path)
if p in self._fs._files:
content = self._fs._files[p]
return {
"isFile": True,
"isDirectory": False,
"size": len(content),
"mtime": "2026-01-01T00:00:00.000Z",
"birthtime": "2026-01-01T00:00:00.000Z",
}
if p.rstrip("/") in self._fs._dirs:
return {
"isFile": False,
"isDirectory": True,
"size": 0,
"mtime": "2026-01-01T00:00:00.000Z",
"birthtime": "2026-01-01T00:00:00.000Z",
}
raise FileNotFoundError(f"Path not found: {path}")
async def mkdir(
self,
*,
session_id: str,
path: str,
recursive: bool | None = None,
mode: int | None = None,
) -> None:
self._fs.mkdir(self._sp(path), recursive=bool(recursive))
async def readdir(self, *, session_id: str, path: str) -> dict[str, Any]:
return {"entries": self._fs.readdir(self._sp(path))}
async def readdir_with_types(self, *, session_id: str, path: str) -> dict[str, Any]:
p = self._sp(path)
names = self._fs.readdir(p)
prefix = p if p.endswith("/") else p + "/"
entries = []
for name in names:
full = prefix + name
is_dir = full in self._fs._dirs or any(
k.startswith(full + "/") for k in self._fs._files
)
entries.append({"name": name, "type": "directory" if is_dir else "file"})
return {"entries": entries}
async def rm(
self,
*,
session_id: str,
path: str,
recursive: bool | None = None,
force: bool | None = None,
) -> None:
self._fs.remove(self._sp(path))
async def rename(self, *, session_id: str, src: str, dest: str) -> None:
self._fs.rename(self._sp(src), self._sp(dest))
# Shared in memory filesystem for all tests in this module
_shared_fs = InMemoryFS()
SESSION_FS_CONFIG = SessionFsConfig(
initial_cwd="/",
session_state_path="/session-state",
conventions="posix",
)
def _make_handler(session: CopilotSession) -> SessionFsHandler:
return InMemorySessionFsHandler(session.session_id, _shared_fs)
@pytest_asyncio.fixture(scope="module", loop_scope="module")
async def ctx(request):
"""Custom context that creates a CopilotClient with SessionFs enabled."""
context = E2ETestContext()
# Override setup to inject session_fs config
context.cli_path = context.cli_path or str(
(
Path(__file__).parents[2]
/ "nodejs"
/ "node_modules"
/ "@github"
/ "copilot"
/ "index.js"
).resolve()
)
env_cli = os.environ.get("COPILOT_CLI_PATH")
if env_cli and Path(env_cli).exists():
context.cli_path = str(Path(env_cli).resolve())
else:
base = Path(__file__).parents[2]
cli = base / "nodejs" / "node_modules" / "@github" / "copilot" / "index.js"
if cli.exists():
context.cli_path = str(cli.resolve())
else:
pytest.skip("CLI not found")
context.home_dir = tempfile.mkdtemp(prefix="copilot-test-config-")
context.work_dir = tempfile.mkdtemp(prefix="copilot-test-work-")
from .testharness.proxy import CapiProxy
context._proxy = CapiProxy()
context.proxy_url = await context._proxy.start()
github_token = (
"fake-token-for-e2e-tests" if os.environ.get("GITHUB_ACTIONS") == "true" else None
)
env = os.environ.copy()
env.update(
{
"COPILOT_API_URL": context.proxy_url,
"XDG_CONFIG_HOME": context.home_dir,
"XDG_STATE_HOME": context.home_dir,
}
)
context._client = CopilotClient(
SubprocessConfig(
cli_path=context.cli_path,
cwd=context.work_dir,
env=env,
github_token=github_token,
),
session_fs=SESSION_FS_CONFIG,
)
yield context
any_failed = request.session.stash.get("any_test_failed", False)
await context.teardown(test_failed=any_failed)
@pytest_asyncio.fixture(autouse=True, loop_scope="module")
async def configure_test(request, ctx):
"""Configure the proxy for each test using session_fs snapshot dir."""
test_name = request.node.name
if test_name.startswith("test_"):
test_name = test_name[5:]
sanitized = re.sub(r"[^a-zA-Z0-9]", "_", test_name).lower()
snapshots_dir = Path(__file__).parents[2] / "test" / "snapshots"
snapshot_path = snapshots_dir / "session_fs" / f"{sanitized}.yaml"
await ctx._proxy.configure(str(snapshot_path.resolve()), ctx.work_dir)
# Clean temp dirs between tests
for item in Path(ctx.home_dir).iterdir():
if item.is_dir():
shutil.rmtree(item, ignore_errors=True)
else:
item.unlink(missing_ok=True)
yield
class TestSessionFs:
async def test_should_route_file_operations_through_the_session_fs_provider(
self, ctx: E2ETestContext
):
session = await ctx.client.create_session(
on_permission_request=PermissionHandler.approve_all,
create_session_fs_handler=_make_handler,
)
msg = await session.send_and_wait("What is 100 + 200?")
assert msg is not None
assert "300" in msg.data.content
await session.disconnect()
events_path = f"/{session.session_id}/session-state/events.jsonl"
content = _shared_fs.read_file(events_path)
assert "300" in content
async def test_should_load_session_data_from_fs_provider_on_resume(self, ctx: E2ETestContext):
session1 = await ctx.client.create_session(
on_permission_request=PermissionHandler.approve_all,
create_session_fs_handler=_make_handler,
)
session_id = session1.session_id
msg = await session1.send_and_wait("What is 50 + 50?")
assert msg is not None
assert "100" in msg.data.content
await session1.disconnect()
events_path = f"/{session_id}/session-state/events.jsonl"
assert _shared_fs.exists(events_path)
session2 = await ctx.client.resume_session(
session_id,
on_permission_request=PermissionHandler.approve_all,
create_session_fs_handler=_make_handler,
)
msg2 = await session2.send_and_wait("What is that times 3?")
await session2.disconnect()
assert msg2 is not None
assert "300" in msg2.data.content