|
| 1 | +// Copyright (c) Microsoft Corporation. All rights reserved. |
| 2 | +// Licensed under the MIT license. |
| 3 | + |
| 4 | +/** |
| 5 | + * Playwright test fixture that launches VS Code via Electron, |
| 6 | + * opens a temporary copy of a test project, and tears everything |
| 7 | + * down after the test. |
| 8 | + * |
| 9 | + * Usage in test files: |
| 10 | + * |
| 11 | + * import { test, expect } from "../fixtures/baseTest"; |
| 12 | + * |
| 13 | + * test("my test", async ({ page }) => { |
| 14 | + * // `page` is a Playwright Page attached to VS Code |
| 15 | + * }); |
| 16 | + */ |
| 17 | + |
| 18 | +import { _electron, test as base, type Page } from "@playwright/test"; |
| 19 | +import { downloadAndUnzipVSCode } from "@vscode/test-electron"; |
| 20 | +import * as fs from "fs-extra"; |
| 21 | +import * as os from "os"; |
| 22 | +import * as path from "path"; |
| 23 | + |
| 24 | +export { expect } from "@playwright/test"; |
| 25 | + |
| 26 | +// Root of the extension source tree |
| 27 | +const EXTENSION_ROOT = path.join(__dirname, "..", "..", ".."); |
| 28 | +// Root of the test data projects |
| 29 | +const TEST_DATA_ROOT = path.join(EXTENSION_ROOT, "test"); |
| 30 | + |
| 31 | +export type TestOptions = { |
| 32 | + /** VS Code version to download, default "stable" */ |
| 33 | + vscodeVersion: string; |
| 34 | + /** Relative path under `test/` to the project to open (e.g. "maven") */ |
| 35 | + testProjectDir: string; |
| 36 | +}; |
| 37 | + |
| 38 | +type TestFixtures = TestOptions & { |
| 39 | + /** Playwright Page connected to the VS Code Electron window */ |
| 40 | + page: Page; |
| 41 | +}; |
| 42 | + |
| 43 | +export const test = base.extend<TestFixtures>({ |
| 44 | + vscodeVersion: [process.env.VSCODE_VERSION || "stable", { option: true }], |
| 45 | + testProjectDir: ["maven", { option: true }], |
| 46 | + |
| 47 | + page: async ({ vscodeVersion, testProjectDir }, use, testInfo) => { |
| 48 | + // 1. Create a temp directory and copy the test project into it. |
| 49 | + const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "java-dep-e2e-")); |
| 50 | + const projectName = path.basename(testProjectDir); |
| 51 | + const projectDir = path.join(tmpDir, projectName); |
| 52 | + fs.copySync(path.join(TEST_DATA_ROOT, testProjectDir), projectDir); |
| 53 | + |
| 54 | + // Write VS Code settings to suppress telemetry prompts and notification noise |
| 55 | + const vscodeDir = path.join(projectDir, ".vscode"); |
| 56 | + fs.ensureDirSync(vscodeDir); |
| 57 | + const settingsPath = path.join(vscodeDir, "settings.json"); |
| 58 | + let existingSettings: Record<string, unknown> = {}; |
| 59 | + if (fs.existsSync(settingsPath)) { |
| 60 | + // settings.json may contain JS-style comments (JSONC), strip them before parsing |
| 61 | + const raw = fs.readFileSync(settingsPath, "utf-8"); |
| 62 | + const stripped = raw.replace(/\/\/.*$/gm, "").replace(/\/\*[\s\S]*?\*\//g, ""); |
| 63 | + try { |
| 64 | + existingSettings = JSON.parse(stripped); |
| 65 | + } catch { |
| 66 | + // If still invalid, start fresh — our injected settings are more important |
| 67 | + existingSettings = {}; |
| 68 | + } |
| 69 | + } |
| 70 | + const mergedSettings = { |
| 71 | + ...existingSettings, |
| 72 | + "telemetry.telemetryLevel": "off", |
| 73 | + "redhat.telemetry.enabled": false, |
| 74 | + "workbench.colorTheme": "Default Dark Modern", |
| 75 | + "update.mode": "none", |
| 76 | + "extensions.ignoreRecommendations": true, |
| 77 | + }; |
| 78 | + fs.writeFileSync(settingsPath, JSON.stringify(mergedSettings, null, 4)); |
| 79 | + |
| 80 | + // 2. Resolve VS Code executable. |
| 81 | + const vscodePath = await downloadAndUnzipVSCode(vscodeVersion); |
| 82 | + // resolveCliArgsFromVSCodeExecutablePath returns CLI-specific args |
| 83 | + // (e.g. --ms-enable-electron-run-as-node) that are unsuitable for |
| 84 | + // Electron UI launch. Extract only --extensions-dir and --user-data-dir. |
| 85 | + const vscodeTestDir = path.join(EXTENSION_ROOT, ".vscode-test"); |
| 86 | + const extensionsDir = path.join(vscodeTestDir, "extensions"); |
| 87 | + const userDataDir = path.join(vscodeTestDir, "user-data"); |
| 88 | + |
| 89 | + // 3. Launch VS Code as an Electron app. |
| 90 | + const electronApp = await _electron.launch({ |
| 91 | + executablePath: vscodePath, |
| 92 | + env: { ...process.env, NODE_ENV: "development" }, |
| 93 | + args: [ |
| 94 | + "--no-sandbox", |
| 95 | + "--disable-gpu-sandbox", |
| 96 | + "--disable-updates", |
| 97 | + "--skip-welcome", |
| 98 | + "--skip-release-notes", |
| 99 | + "--disable-workspace-trust", |
| 100 | + "--password-store=basic", |
| 101 | + // Suppress notifications that block UI interactions |
| 102 | + "--disable-telemetry", |
| 103 | + `--extensions-dir=${extensionsDir}`, |
| 104 | + `--user-data-dir=${userDataDir}`, |
| 105 | + `--extensionDevelopmentPath=${EXTENSION_ROOT}`, |
| 106 | + projectDir, |
| 107 | + ], |
| 108 | + }); |
| 109 | + |
| 110 | + const page = await electronApp.firstWindow(); |
| 111 | + |
| 112 | + // Auto-dismiss Electron native dialogs (e.g. redhat.java refactoring |
| 113 | + // confirmation, delete file confirmation). These dialogs are outside |
| 114 | + // the renderer DOM and cannot be handled via Playwright Page API. |
| 115 | + // Monkey-patch dialog.showMessageBox to find and click the confirm |
| 116 | + // button by label, falling back to the first button. |
| 117 | + await electronApp.evaluate(({ dialog }) => { |
| 118 | + const confirmLabels = /^(OK|Delete|Move to Recycle Bin|Move to Trash)$/i; |
| 119 | + dialog.showMessageBox = async (_win: any, opts: any) => { |
| 120 | + const options = opts || _win; |
| 121 | + const buttons: string[] = options?.buttons || []; |
| 122 | + let idx = buttons.findIndex((b: string) => confirmLabels.test(b)); |
| 123 | + if (idx < 0) idx = 0; |
| 124 | + return { response: idx, checkboxChecked: true }; |
| 125 | + }; |
| 126 | + dialog.showMessageBoxSync = (_win: any, opts: any) => { |
| 127 | + const options = opts || _win; |
| 128 | + const buttons: string[] = options?.buttons || []; |
| 129 | + let idx = buttons.findIndex((b: string) => confirmLabels.test(b)); |
| 130 | + if (idx < 0) idx = 0; |
| 131 | + return idx; |
| 132 | + }; |
| 133 | + }); |
| 134 | + |
| 135 | + // Dismiss any startup notifications/dialogs before handing off to tests |
| 136 | + await page.waitForTimeout(3_000); |
| 137 | + await dismissAllNotifications(page); |
| 138 | + |
| 139 | + // 4. Optional tracing |
| 140 | + if (testInfo.retry > 0 || !process.env.CI) { |
| 141 | + await page.context().tracing.start({ screenshots: true, snapshots: true, title: testInfo.title }); |
| 142 | + } |
| 143 | + |
| 144 | + // ---- hand off to the test ---- |
| 145 | + await use(page); |
| 146 | + |
| 147 | + // ---- teardown ---- |
| 148 | + // Save trace on failure/retry |
| 149 | + if (testInfo.status !== "passed" || testInfo.retry > 0) { |
| 150 | + const tracePath = testInfo.outputPath("trace.zip"); |
| 151 | + try { |
| 152 | + await page.context().tracing.stop({ path: tracePath }); |
| 153 | + testInfo.attachments.push({ name: "trace", path: tracePath, contentType: "application/zip" }); |
| 154 | + } catch { |
| 155 | + // Tracing may not have been started |
| 156 | + } |
| 157 | + } |
| 158 | + |
| 159 | + await electronApp.close(); |
| 160 | + |
| 161 | + // Clean up temp directory |
| 162 | + try { |
| 163 | + fs.rmSync(tmpDir, { force: true, recursive: true }); |
| 164 | + } catch (e) { |
| 165 | + console.warn(`Warning: failed to clean up ${tmpDir}: ${e}`); |
| 166 | + } |
| 167 | + }, |
| 168 | +}); |
| 169 | + |
| 170 | +/** |
| 171 | + * Dismiss all VS Code notification toasts (telemetry prompts, theme suggestions, etc.). |
| 172 | + * These notifications can steal focus and block Quick Open / Command Palette interactions. |
| 173 | + */ |
| 174 | +async function dismissAllNotifications(page: Page): Promise<void> { |
| 175 | + try { |
| 176 | + // Click "Clear All Notifications" if the notification center button is visible |
| 177 | + const clearAll = page.locator(".notifications-toasts .codicon-notifications-clear-all, .notification-toast .codicon-close"); |
| 178 | + let count = await clearAll.count().catch(() => 0); |
| 179 | + while (count > 0) { |
| 180 | + await clearAll.first().click(); |
| 181 | + await page.waitForTimeout(500); |
| 182 | + count = await clearAll.count().catch(() => 0); |
| 183 | + } |
| 184 | + |
| 185 | + // Also try the command palette approach as a fallback |
| 186 | + const notificationToasts = page.locator(".notification-toast"); |
| 187 | + if (await notificationToasts.count().catch(() => 0) > 0) { |
| 188 | + // Use keyboard shortcut to clear all notifications |
| 189 | + await page.keyboard.press("Control+Shift+P"); |
| 190 | + const input = page.locator(".quick-input-widget input.input"); |
| 191 | + if (await input.isVisible({ timeout: 3_000 }).catch(() => false)) { |
| 192 | + await input.fill("Notifications: Clear All Notifications"); |
| 193 | + await page.waitForTimeout(500); |
| 194 | + await input.press("Enter"); |
| 195 | + await page.waitForTimeout(500); |
| 196 | + } |
| 197 | + } |
| 198 | + } catch { |
| 199 | + // Best effort |
| 200 | + } |
| 201 | +} |
0 commit comments