-
Notifications
You must be signed in to change notification settings - Fork 1.3k
Expand file tree
/
Copy pathtest_copilot_request_handler_e2e.py
More file actions
284 lines (233 loc) · 9.97 KB
/
Copy pathtest_copilot_request_handler_e2e.py
File metadata and controls
284 lines (233 loc) · 9.97 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
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# --------------------------------------------------------------------------------------------
"""E2E test for the idiomatic ``CopilotRequestHandler`` forwarding seams.
Mirrors ``nodejs/test/e2e/copilot_request_handler.e2e.test.ts``. A single
handler subclass services BOTH transports against a per-test fake upstream:
* HTTP — :meth:`send_request` rewrites the request to the local HTTP upstream,
mutates an outbound and a response header, and forwards via httpx.
* WebSocket — :meth:`open_websocket` rewrites the URL to the local WebSocket
upstream and returns a forwarding handler that counts messages in both
directions.
Unlike the other inference tests (which fabricate responses inline), this one
exercises the default httpx / ``websockets`` forwarding machinery against a
real socket, proving the full chain runtime → handler → upstream → handler →
runtime is intact for whichever transport the agent turn selects.
"""
from __future__ import annotations
import json
import os
import threading
from dataclasses import dataclass, field
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
import httpx
import pytest
import pytest_asyncio
from websockets.asyncio.server import serve as ws_serve
from copilot import (
CopilotClient,
CopilotRequestContext,
CopilotRequestHandler,
CopilotWebSocketForwarder,
RuntimeConnection,
)
from copilot.session import PermissionHandler
from ._copilot_request_helpers import assistant_text, model_catalog, responses_events
from .testharness import E2ETestContext
pytestmark = pytest.mark.asyncio(loop_scope="module")
HTTP_TEXT = "OK from synthetic HTTP upstream."
WS_TEXT = "OK from synthetic WS upstream."
@dataclass
class _Counters:
http_requests: int = 0
http_responses: int = 0
ws_request_messages: int = 0
ws_response_messages: int = 0
@dataclass
class _Upstream:
http_url: str
ws_url: str
_http_server: ThreadingHTTPServer
_http_thread: threading.Thread
_ws_server: object
ws_requests: list[int] = field(default_factory=lambda: [0])
@property
def ws_request_count(self) -> int:
return self.ws_requests[0]
async def close(self) -> None:
self._http_server.shutdown()
self._http_thread.join(timeout=5)
self._http_server.server_close()
self._ws_server.close() # type: ignore[attr-defined]
await self._ws_server.wait_closed() # type: ignore[attr-defined]
def _sse_body(text: str, resp_id: str) -> bytes:
out = "".join(
f"event: {event['type']}\ndata: {json.dumps(event)}\n\n"
for event in responses_events(text, resp_id)
)
return out.encode("utf-8")
async def _start_fake_upstream() -> _Upstream:
class _Handler(BaseHTTPRequestHandler):
def log_message(self, *_args): # noqa: ANN002 - silence default logging
pass
def _send(self, status: int, content_type: str, body: bytes) -> None:
self.send_response(status)
self.send_header("content-type", content_type)
self.send_header("content-length", str(len(body)))
self.end_headers()
self.wfile.write(body)
def _route(self) -> None:
path = self.path.split("?", 1)[0].lower()
length = int(self.headers.get("content-length") or 0)
if length:
self.rfile.read(length)
if path.endswith("/models"):
self._send(
200,
"application/json",
json.dumps(
model_catalog(supported_endpoints=["/responses", "ws:/responses"])
).encode("utf-8"),
)
return
if path.endswith("/models/session"):
self._send(200, "application/json", b"{}")
return
if "/policy" in path:
self._send(
200,
"application/json",
json.dumps({"state": "enabled"}).encode("utf-8"),
)
return
if path.endswith("/responses"):
self._send(200, "text/event-stream", _sse_body(HTTP_TEXT, "resp_stub_http"))
return
self._send(
404,
"application/json",
json.dumps({"error": "not_found", "path": path}).encode("utf-8"),
)
def do_GET(self): # noqa: N802
self._route()
def do_POST(self): # noqa: N802
self._route()
http_server = ThreadingHTTPServer(("127.0.0.1", 0), _Handler)
http_port = http_server.server_address[1]
http_thread = threading.Thread(target=http_server.serve_forever, daemon=True)
http_thread.start()
ws_requests = [0]
async def ws_handler(connection) -> None:
async for _raw in connection:
ws_requests[0] += 1
for event in responses_events(WS_TEXT, "resp_stub_ws"):
await connection.send(json.dumps(event))
ws_server = await ws_serve(ws_handler, "127.0.0.1", 0)
ws_port = ws_server.sockets[0].getsockname()[1]
return _Upstream(
http_url=f"http://127.0.0.1:{http_port}",
ws_url=f"ws://127.0.0.1:{ws_port}",
_http_server=http_server,
_http_thread=http_thread,
_ws_server=ws_server,
ws_requests=ws_requests,
)
class _CountingSocketHandler(CopilotWebSocketForwarder):
"""Forwarding WebSocket handler that counts messages in both directions."""
def __init__(self, ctx: CopilotRequestContext, counters: _Counters) -> None:
super().__init__(ctx)
self._counters = counters
async def send_request_message(self, data: str | bytes) -> None:
self._counters.ws_request_messages += 1
await super().send_request_message(data)
async def send_response_message(self, data: str | bytes) -> None:
self._counters.ws_response_messages += 1
await super().send_response_message(data)
class _TestHandler(CopilotRequestHandler):
def __init__(self, upstream: _Upstream, counters: _Counters) -> None:
self._upstream = upstream
self._counters = counters
self._client = httpx.AsyncClient(timeout=None, follow_redirects=False)
def _rewrite_http(self, url: httpx.URL) -> httpx.URL:
up = httpx.URL(self._upstream.http_url)
return url.copy_with(scheme=up.scheme, host=up.host, port=up.port)
def _rewrite_ws(self, url: str) -> str:
parsed = httpx.URL(url)
up = httpx.URL(self._upstream.ws_url)
return str(parsed.copy_with(scheme=up.scheme, host=up.host, port=up.port))
async def send_request(
self, request: httpx.Request, ctx: CopilotRequestContext
) -> httpx.Response:
self._counters.http_requests += 1
headers = dict(request.headers)
headers["x-test-mutated"] = "1"
rewritten = httpx.Request(
request.method,
self._rewrite_http(request.url),
headers=headers,
content=request.content,
)
response = await self._client.send(rewritten, stream=True)
self._counters.http_responses += 1
response.headers["x-test-response-mutated"] = "1"
return response
async def open_websocket(self, ctx: CopilotRequestContext):
ctx.url = self._rewrite_ws(ctx.url)
return _CountingSocketHandler(ctx, self._counters)
async def aclose(self) -> None:
await self._client.aclose()
@dataclass
class _HandlerFixture:
client: CopilotClient
upstream: _Upstream
counters: _Counters
@pytest_asyncio.fixture(loop_scope="module")
async def handler_fixture(ctx: E2ETestContext):
upstream = await _start_fake_upstream()
counters = _Counters()
handler = _TestHandler(upstream, counters)
github_token = (
"fake-token-for-e2e-tests" if os.environ.get("GITHUB_ACTIONS") == "true" else None
)
env = {**ctx.get_env(), "COPILOT_EXP_COPILOT_CLI_WEBSOCKET_RESPONSES": "true"}
client = CopilotClient(
connection=RuntimeConnection.for_stdio(path=ctx.cli_path),
working_directory=ctx.work_dir,
env=env,
github_token=github_token,
request_handler=handler,
)
try:
yield _HandlerFixture(client=client, upstream=upstream, counters=counters)
finally:
try:
await client.stop()
except Exception:
# Best-effort teardown during fixture cleanup.
pass
await handler.aclose()
await upstream.close()
class TestCopilotRequestHandler:
async def test_services_http_and_websocket_via_one_handler(self, handler_fixture):
fx = handler_fixture
await fx.client.start()
session = await fx.client.create_session(
on_permission_request=PermissionHandler.approve_all
)
text = ""
try:
result = await session.send_and_wait("Say OK.")
text = assistant_text(result)
finally:
await session.disconnect()
# The HTTP seam fired — the runtime issued model-layer GETs (catalog,
# policy) and possibly a single-shot inference through send_request.
assert fx.counters.http_requests > 0, "expected send_request to fire"
assert fx.counters.http_responses > 0, "expected send_request response mutation to fire"
# The WebSocket seam fired — the main agent turn went over the WS path
# and we observed messages in both directions.
assert fx.counters.ws_request_messages > 0, "expected runtime → upstream ws messages"
assert fx.counters.ws_response_messages > 0, "expected upstream → runtime ws messages"
assert fx.upstream.ws_request_count > 0, "expected upstream WS to receive request messages"
# Validate the final assistant response arrived (guards against truncated captures)
assert "OK from synthetic" in text and "upstream" in text