-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathE2ETestContext.java
More file actions
470 lines (426 loc) · 17.3 KB
/
E2ETestContext.java
File metadata and controls
470 lines (426 loc) · 17.3 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
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
*--------------------------------------------------------------------------------------------*/
package com.github.copilot.sdk;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Logger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import com.github.copilot.sdk.json.CopilotClientOptions;
/**
* E2E test context that manages the test environment including the CapiProxy,
* working directories, and CLI path.
*
* <p>
* This provides a complete test environment similar to the Node.js, .NET, Go,
* and Python SDK test harnesses. It manages:
* </p>
* <ul>
* <li>A replaying CapiProxy for deterministic API responses</li>
* <li>Temporary home and work directories for test isolation</li>
* <li>Environment variables for the Copilot CLI</li>
* </ul>
*
* <p>
* Usage example:
* </p>
*
* <pre>
* {@code
* try (E2ETestContext ctx = E2ETestContext.create()) {
* ctx.configureForTest("tools", "my_test_name");
*
* try (CopilotClient client = ctx.createClient()) {
* CopilotSession session = client
* .createSession(new SessionConfig().setOnPermissionRequest(PermissionHandler.APPROVE_ALL)).get();
* // ... run test ...
* }
* }
* }
* </pre>
*/
public class E2ETestContext implements AutoCloseable {
private static final Logger LOG = Logger.getLogger(E2ETestContext.class.getName());
private static final Pattern SNAKE_CASE = Pattern.compile("[^a-zA-Z0-9]");
private static final Pattern USER_CONTENT_PATTERN = Pattern
.compile("^\\s+-\\s+role:\\s+user\\s*$\\s+content:\\s*(.+?)$", Pattern.MULTILINE);
private final String cliPath;
private final Path homeDir;
private final Path workDir;
private String proxyUrl;
private final CapiProxy proxy;
private final Path repoRoot;
private Path currentSnapshotFile;
private E2ETestContext(String cliPath, Path homeDir, Path workDir, String proxyUrl, CapiProxy proxy,
Path repoRoot) {
this.cliPath = cliPath;
this.homeDir = homeDir;
this.workDir = workDir;
this.proxyUrl = proxyUrl;
this.proxy = proxy;
this.repoRoot = repoRoot;
}
/**
* Creates a new E2E test context.
*
* @return the test context
* @throws IOException
* if setup fails
* @throws InterruptedException
* if setup is interrupted
*/
public static E2ETestContext create() throws IOException, InterruptedException {
Path repoRoot = findRepoRoot();
String cliPath = getCliPath(repoRoot);
Path tempDir = Paths.get(System.getProperty("java.io.tmpdir"));
Path homeDir = Files.createTempDirectory(tempDir, "copilot-test-config-");
Path workDir = Files.createTempDirectory(tempDir, "copilot-test-work-");
CapiProxy proxy = new CapiProxy();
String proxyUrl = proxy.start();
return new E2ETestContext(cliPath, homeDir, workDir, proxyUrl, proxy, repoRoot);
}
/**
* Gets the Copilot CLI path.
*/
public String getCliPath() {
return cliPath;
}
/**
* Gets the temporary home directory for test isolation.
*/
public Path getHomeDir() {
return homeDir;
}
/**
* Gets the temporary working directory for tests.
*/
public Path getWorkDir() {
return workDir;
}
/**
* Gets the proxy URL.
*/
public String getProxyUrl() {
return proxyUrl;
}
/**
* Configures the proxy for a specific test.
*
* @param testFile
* the test category folder (e.g., "tools", "session", "permissions")
* @param testName
* the test method name (will be converted to snake_case)
* @throws IOException
* if configuration fails
* @throws InterruptedException
* if configuration is interrupted
*/
public void configureForTest(String testFile, String testName) throws IOException, InterruptedException {
// Restart the proxy if it has crashed
ensureProxyAlive();
// Convert test method names to lowercase snake_case for snapshot filenames
// to avoid case collisions on case-insensitive filesystems (macOS/Windows)
String sanitizedName = SNAKE_CASE.matcher(testName).replaceAll("_").toLowerCase();
Path snapshotFile = repoRoot.resolve("test").resolve("snapshots").resolve(testFile)
.resolve(sanitizedName + ".yaml");
// Validate snapshot exists - fail fast with a clear message
if (!Files.exists(snapshotFile)) {
Path snapshotsDir = repoRoot.resolve("test").resolve("snapshots").resolve(testFile);
String availableSnapshots = "";
if (Files.exists(snapshotsDir)) {
try (var files = Files.list(snapshotsDir)) {
availableSnapshots = files.filter(p -> p.toString().endsWith(".yaml"))
.map(p -> p.getFileName().toString().replace(".yaml", "")).sorted()
.reduce((a, b) -> a + ", " + b).orElse("<none>");
}
}
throw new IOException(String.format(
"Snapshot file not found: %s%n" + "Category: %s, Test: %s (sanitized: %s)%n"
+ "Available snapshots in '%s/': %s%n"
+ "Ensure the snapshot exists and the test name matches exactly.",
snapshotFile, testFile, testName, sanitizedName, testFile, availableSnapshots));
}
this.currentSnapshotFile = snapshotFile;
proxy.configure(snapshotFile.toString(), workDir.toString());
// Log expected prompts to help debug prompt mismatch issues
List<String> expectedPrompts = getExpectedUserPrompts();
if (!expectedPrompts.isEmpty()) {
LOG.info(() -> String.format("Configured snapshot '%s/%s' expects prompts: %s", testFile, sanitizedName,
expectedPrompts));
}
}
/**
* Gets the expected user prompts from the current snapshot file.
* <p>
* This is useful for debugging when tests fail with "No cached response found"
* errors from CapiProxy. The prompts in your test must match these exactly.
* </p>
*
* @return list of expected user prompt strings, or empty list if none found
*/
public List<String> getExpectedUserPrompts() {
if (currentSnapshotFile == null || !Files.exists(currentSnapshotFile)) {
return List.of();
}
try {
String content = Files.readString(currentSnapshotFile);
List<String> prompts = new ArrayList<>();
Matcher matcher = USER_CONTENT_PATTERN.matcher(content);
while (matcher.find()) {
String prompt = matcher.group(1).trim();
// Remove quotes if present
if ((prompt.startsWith("\"") && prompt.endsWith("\""))
|| (prompt.startsWith("'") && prompt.endsWith("'"))) {
prompt = prompt.substring(1, prompt.length() - 1);
}
if (!prompts.contains(prompt)) {
prompts.add(prompt);
}
}
return prompts;
} catch (IOException e) {
LOG.warning("Failed to read snapshot file: " + e.getMessage());
return List.of();
}
}
/**
* Ensures the proxy is alive, restarting it if necessary.
*
* @throws IOException
* if the proxy cannot be restarted
* @throws InterruptedException
* if interrupted during restart
*/
public void ensureProxyAlive() throws IOException, InterruptedException {
if (!proxy.isAlive()) {
proxyUrl = proxy.restart();
}
}
/**
* Gets the captured HTTP exchanges from the proxy.
*
* @return list of exchange maps
* @throws IOException
* if the request fails
* @throws InterruptedException
* if the request is interrupted
*/
public List<Map<String, Object>> getExchanges() throws IOException, InterruptedException {
return proxy.getExchanges();
}
/**
* Gets the environment variables needed for the Copilot CLI.
*
* @return map of environment variables
*/
public Map<String, String> getEnvironment() {
Map<String, String> env = new HashMap<>(System.getenv());
env.put("COPILOT_API_URL", proxyUrl);
env.put("COPILOT_HOME", homeDir.toString());
env.put("XDG_CONFIG_HOME", homeDir.toString());
env.put("XDG_STATE_HOME", homeDir.toString());
return env;
}
/**
* Creates a CopilotClient configured for this test context.
*
* @return a new CopilotClient
*/
public CopilotClient createClient() {
CopilotClientOptions options = new CopilotClientOptions().setCliPath(cliPath).setCwd(workDir.toString())
.setEnvironment(getEnvironment());
// In CI (GitHub Actions), use a fake token to avoid auth issues
String ci = System.getenv("GITHUB_ACTIONS");
if (ci != null && !ci.isEmpty()) {
options.setGitHubToken("fake-token-for-e2e-tests");
}
return new CopilotClient(options);
}
/**
* Creates a CopilotClient with the given options, applied on top of the default
* options for this test context.
*
* @param options
* options to apply; environment and cliPath will be set from the
* context if not already set
* @return a new CopilotClient
*/
public CopilotClient createClient(CopilotClientOptions options) {
if (options.getCliPath() == null) {
options.setCliPath(cliPath);
}
if (options.getCwd() == null) {
options.setCwd(workDir.toString());
}
if (options.getEnvironment() == null || options.getEnvironment().isEmpty()) {
options.setEnvironment(getEnvironment());
}
// In CI (GitHub Actions), use a fake token to avoid auth issues
String ci = System.getenv("GITHUB_ACTIONS");
if (ci != null && !ci.isEmpty() && options.getGitHubToken() == null) {
options.setGitHubToken("fake-token-for-e2e-tests");
}
return new CopilotClient(options);
}
/**
* Configures the proxy to return a specific Copilot user response for a given
* token. Used for per-session authentication tests.
*
* @param token
* the GitHub token
* @param login
* the user login
* @param copilotPlan
* the Copilot plan
* @param apiUrl
* the API URL for the user endpoints
* @param telemetryUrl
* the telemetry URL
* @param analyticsTrackingId
* the analytics tracking ID
* @throws IOException
* if the request fails
* @throws InterruptedException
* if the request is interrupted
*/
public void setCopilotUserByToken(String token, String login, String copilotPlan, String apiUrl,
String telemetryUrl, String analyticsTrackingId) throws IOException, InterruptedException {
ensureProxyAlive();
proxy.setCopilotUserByToken(token, login, copilotPlan, apiUrl, telemetryUrl, analyticsTrackingId);
}
/**
* Initializes the proxy state without loading a snapshot.
* <p>
* Use this for tests that need the proxy to be active (e.g., for per-session
* auth token resolution via {@code /copilot_internal/user}) but do not make AI
* completion requests and therefore have no snapshot to load.
* </p>
* <p>
* The proxy requires its internal {@code state} to be initialized before it can
* handle most endpoints. Without this call the proxy throws an error and
* returns HTTP 500 for any request that arrives before a {@code /config} POST
* has been made.
* </p>
*
* @throws IOException
* if the proxy configuration request fails
* @throws InterruptedException
* if the request is interrupted
*/
public void initializeProxy() throws IOException, InterruptedException {
ensureProxyAlive();
// Pass a non-existent snapshot path. The proxy initializes its state even when
// the file is absent (storedData simply remains undefined), which is fine for
// tests that never make AI chat-completion requests.
proxy.configure(workDir.resolve("no-snapshot.yaml").toString(), workDir.toString());
}
@Override
public void close() throws Exception {
proxy.stop();
// Clean up temp directories (best effort)
deleteRecursively(homeDir);
deleteRecursively(workDir);
}
private static Path findRepoRoot() throws IOException {
// First, check for copilot.sdk.dir system property (set by Maven during tests)
String sdkDir = System.getProperty("copilot.sdk.dir");
if (sdkDir != null && !sdkDir.isEmpty()) {
Path sdkPath = Paths.get(sdkDir);
if (Files.exists(sdkPath)) {
return sdkPath;
}
}
// Fallback: search up from current directory
Path dir = Paths.get(System.getProperty("user.dir"));
while (dir != null) {
if (Files.exists(dir.resolve("nodejs")) && Files.exists(dir.resolve("test").resolve("harness"))) {
return dir;
}
dir = dir.getParent();
}
throw new IOException("Could not find repository root. Either set copilot.sdk.dir system property "
+ "or run from within the copilot-sdk repository.");
}
private static String getCliPath(Path repoRoot) throws IOException {
// Try environment variable first (explicit override)
String envPath = System.getenv("COPILOT_CLI_PATH");
if (envPath != null && !envPath.isEmpty()) {
return envPath;
}
// Try test harness platform-specific binary (preferred as it has correct
// version)
String os = System.getProperty("os.name").toLowerCase();
String arch = System.getProperty("os.arch").toLowerCase();
String platform = os.contains("mac") ? "darwin" : os.contains("win") ? "win32" : "linux";
String cpuArch = arch.contains("aarch64") || arch.contains("arm64") ? "arm64" : "x64";
Path platformBinary = repoRoot
.resolve("test/harness/node_modules/@github/copilot-" + platform + "-" + cpuArch + "/copilot");
if (os.contains("win")) {
platformBinary = repoRoot
.resolve("test/harness/node_modules/@github/copilot-" + platform + "-" + cpuArch + "/copilot.exe");
}
if (Files.exists(platformBinary)) {
return platformBinary.toString();
}
// Try test harness npm-loader.js
Path harnessCliPath = repoRoot.resolve("test/harness/node_modules/@github/copilot/npm-loader.js");
if (Files.exists(harnessCliPath)) {
return harnessCliPath.toString();
}
// Try nodejs installation
Path cliPath = repoRoot.resolve("nodejs/node_modules/@github/copilot/index.js");
if (Files.exists(cliPath)) {
return cliPath.toString();
}
// Fallback: try to find 'copilot' in PATH
String copilotInPath = findCopilotInPath();
if (copilotInPath != null) {
return copilotInPath;
}
throw new IOException("CLI not found. Either install 'copilot' globally, set COPILOT_CLI_PATH, "
+ "or run 'npm install' in the nodejs directory or test/harness directory.");
}
private static String findCopilotInPath() {
try {
String command = System.getProperty("os.name").toLowerCase().contains("win") ? "where" : "which";
ProcessBuilder pb = new ProcessBuilder(command, "copilot");
pb.redirectErrorStream(true);
Process process = pb.start();
try (BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()))) {
String line = reader.readLine();
int exitCode = process.waitFor();
if (exitCode == 0 && line != null && !line.isEmpty()) {
return line.trim();
}
}
} catch (Exception e) {
// Ignore - copilot not found in PATH
}
return null;
}
private static void deleteRecursively(Path path) {
try {
if (Files.exists(path)) {
Files.walk(path).sorted((a, b) -> b.compareTo(a)) // Reverse order to delete children first
.forEach(p -> {
try {
Files.delete(p);
} catch (IOException e) {
// Best effort
}
});
}
} catch (IOException e) {
// Best effort
}
}
}