|
| 1 | +import fs from "fs"; |
| 2 | +import path from "path"; |
| 3 | +import os from "os"; |
| 4 | +import { test as base, expect, chromium, type BrowserContext } from "@playwright/test"; |
| 5 | +import { installScriptByCode } from "./utils"; |
| 6 | + |
| 7 | +const test = base.extend<{ |
| 8 | + context: BrowserContext; |
| 9 | + extensionId: string; |
| 10 | +}>({ |
| 11 | + // eslint-disable-next-line no-empty-pattern |
| 12 | + context: async ({}, use) => { |
| 13 | + const pathToExtension = path.resolve(__dirname, "../dist/ext"); |
| 14 | + const userDataDir = fs.mkdtempSync(path.join(os.tmpdir(), "pw-ext-")); |
| 15 | + const chromeArgs = [`--disable-extensions-except=${pathToExtension}`, `--load-extension=${pathToExtension}`]; |
| 16 | + |
| 17 | + // Phase 1: Enable user scripts permission |
| 18 | + const ctx1 = await chromium.launchPersistentContext(userDataDir, { |
| 19 | + headless: false, |
| 20 | + args: ["--headless=new", ...chromeArgs], |
| 21 | + }); |
| 22 | + let [bg] = ctx1.serviceWorkers(); |
| 23 | + if (!bg) bg = await ctx1.waitForEvent("serviceworker"); |
| 24 | + const extensionId = bg.url().split("/")[2]; |
| 25 | + const extPage = await ctx1.newPage(); |
| 26 | + await extPage.goto("chrome://extensions/"); |
| 27 | + await extPage.waitForLoadState("domcontentloaded"); |
| 28 | + await extPage.waitForTimeout(1_000); |
| 29 | + await extPage.evaluate(async (id) => { |
| 30 | + await (chrome as any).developerPrivate.updateExtensionConfiguration({ |
| 31 | + extensionId: id, |
| 32 | + userScriptsAccess: true, |
| 33 | + }); |
| 34 | + }, extensionId); |
| 35 | + await extPage.close(); |
| 36 | + await ctx1.close(); |
| 37 | + |
| 38 | + // Phase 2: Relaunch with user scripts enabled |
| 39 | + const context = await chromium.launchPersistentContext(userDataDir, { |
| 40 | + headless: false, |
| 41 | + args: ["--headless=new", ...chromeArgs], |
| 42 | + }); |
| 43 | + await use(context); |
| 44 | + await context.close(); |
| 45 | + fs.rmSync(userDataDir, { recursive: true, force: true }); |
| 46 | + }, |
| 47 | + extensionId: async ({ context }, use) => { |
| 48 | + let [background] = context.serviceWorkers(); |
| 49 | + if (!background) background = await context.waitForEvent("serviceworker"); |
| 50 | + const extensionId = background.url().split("/")[2]; |
| 51 | + const initPage = await context.newPage(); |
| 52 | + await initPage.goto(`chrome-extension://${extensionId}/src/options.html`); |
| 53 | + await initPage.waitForLoadState("domcontentloaded"); |
| 54 | + await initPage.evaluate(() => localStorage.setItem("firstUse", "false")); |
| 55 | + await initPage.close(); |
| 56 | + await use(extensionId); |
| 57 | + }, |
| 58 | +}); |
| 59 | + |
| 60 | +/** Strip SRI hashes and replace slow CDN with faster alternative */ |
| 61 | +function patchScriptCode(code: string): string { |
| 62 | + return code |
| 63 | + .replace(/^(\/\/\s*@(?:require|resource)\s+.*?)#sha(?:256|384|512)[=-][^\s]+/gm, "$1") |
| 64 | + .replace(/https:\/\/cdn\.jsdelivr\.net\/npm\//g, "https://unpkg.com/"); |
| 65 | +} |
| 66 | + |
| 67 | +/** |
| 68 | + * Auto-approve permission confirm dialogs opened by the extension. |
| 69 | + * Listens for new pages matching confirm.html and clicks the |
| 70 | + * "permanent allow all" button (type=4, allow=true). |
| 71 | + */ |
| 72 | +function autoApprovePermissions(context: BrowserContext): void { |
| 73 | + context.on("page", async (page) => { |
| 74 | + const url = page.url(); |
| 75 | + if (!url.includes("confirm.html")) return; |
| 76 | + |
| 77 | + try { |
| 78 | + await page.waitForLoadState("domcontentloaded"); |
| 79 | + // Click the "permanent allow" button (4th success button = type=5 permanent allow this) |
| 80 | + // The buttons in order are: allow_once(1), temporary_allow(3), permanent_allow(5) |
| 81 | + // We want "permanent_allow" which is the 3rd success button |
| 82 | + const successButtons = page.locator("button.arco-btn-status-success"); |
| 83 | + await successButtons.first().waitFor({ timeout: 5_000 }); |
| 84 | + // Find and click the last always-visible success button (permanent_allow, type=5) |
| 85 | + // Button order: allow_once(type=1), temporary_allow(type=3), permanent_allow(type=5) |
| 86 | + // Index 2 = permanent_allow (always visible) |
| 87 | + const count = await successButtons.count(); |
| 88 | + if (count >= 3) { |
| 89 | + // permanent_allow is at index 2 |
| 90 | + await successButtons.nth(2).click(); |
| 91 | + } else { |
| 92 | + // Fallback: click the last visible success button |
| 93 | + await successButtons.last().click(); |
| 94 | + } |
| 95 | + console.log("[autoApprove] Permission approved on confirm page"); |
| 96 | + } catch (e) { |
| 97 | + console.log("[autoApprove] Failed to approve:", e); |
| 98 | + } |
| 99 | + }); |
| 100 | +} |
| 101 | + |
| 102 | +/** Run a test script on the target page and collect console results */ |
| 103 | +async function runTestScript( |
| 104 | + context: BrowserContext, |
| 105 | + extensionId: string, |
| 106 | + scriptFile: string, |
| 107 | + targetUrl: string, |
| 108 | + timeoutMs: number |
| 109 | +): Promise<{ passed: number; failed: number; logs: string[] }> { |
| 110 | + let code = fs.readFileSync(path.join(__dirname, `../example/tests/${scriptFile}`), "utf-8"); |
| 111 | + code = patchScriptCode(code); |
| 112 | + |
| 113 | + await installScriptByCode(context, extensionId, code); |
| 114 | + |
| 115 | + // Start auto-approving permission dialogs |
| 116 | + autoApprovePermissions(context); |
| 117 | + |
| 118 | + const page = await context.newPage(); |
| 119 | + const logs: string[] = []; |
| 120 | + page.on("console", (msg) => logs.push(msg.text())); |
| 121 | + |
| 122 | + await page.goto(targetUrl, { waitUntil: "domcontentloaded" }); |
| 123 | + |
| 124 | + // Wait for test results to appear in console |
| 125 | + const deadline = Date.now() + timeoutMs; |
| 126 | + let passed = -1; |
| 127 | + let failed = -1; |
| 128 | + while (Date.now() < deadline) { |
| 129 | + for (const log of logs) { |
| 130 | + const passMatch = log.match(/通过[::]\s*(\d+)/); |
| 131 | + const failMatch = log.match(/失败[::]\s*(\d+)/); |
| 132 | + if (passMatch) passed = parseInt(passMatch[1], 10); |
| 133 | + if (failMatch) failed = parseInt(failMatch[1], 10); |
| 134 | + } |
| 135 | + if (passed >= 0 && failed >= 0) break; |
| 136 | + await page.waitForTimeout(500); |
| 137 | + } |
| 138 | + |
| 139 | + await page.close(); |
| 140 | + return { passed, failed, logs }; |
| 141 | +} |
| 142 | + |
| 143 | +const TARGET_URL = "https://content-security-policy.com/"; |
| 144 | + |
| 145 | +test.describe("GM API", () => { |
| 146 | + // Two-phase launch + script install + network fetches + permission dialogs |
| 147 | + test.setTimeout(300_000); |
| 148 | + |
| 149 | + test("GM_ sync API tests (gm_api_test.js)", async ({ context, extensionId }) => { |
| 150 | + const { passed, failed, logs } = await runTestScript(context, extensionId, "gm_api_test.js", TARGET_URL, 90_000); |
| 151 | + |
| 152 | + console.log(`[gm_api_test] passed=${passed}, failed=${failed}`); |
| 153 | + if (failed !== 0) { |
| 154 | + console.log("[gm_api_test] logs:", logs.join("\n")); |
| 155 | + } |
| 156 | + expect(failed, "Some GM_ sync API tests failed").toBe(0); |
| 157 | + expect(passed, "No test results found - script may not have run").toBeGreaterThan(0); |
| 158 | + }); |
| 159 | + |
| 160 | + test("GM.* async API tests (gm_api_async_test.js)", async ({ context, extensionId }) => { |
| 161 | + const { passed, failed, logs } = await runTestScript( |
| 162 | + context, |
| 163 | + extensionId, |
| 164 | + "gm_api_async_test.js", |
| 165 | + TARGET_URL, |
| 166 | + 90_000 |
| 167 | + ); |
| 168 | + |
| 169 | + console.log(`[gm_api_async_test] passed=${passed}, failed=${failed}`); |
| 170 | + if (failed !== 0) { |
| 171 | + console.log("[gm_api_async_test] logs:", logs.join("\n")); |
| 172 | + } |
| 173 | + expect(failed, "Some GM.* async API tests failed").toBe(0); |
| 174 | + expect(passed, "No test results found - script may not have run").toBeGreaterThan(0); |
| 175 | + }); |
| 176 | + |
| 177 | + test("Content inject tests (inject_content_test.js)", async ({ context, extensionId }) => { |
| 178 | + const { passed, failed, logs } = await runTestScript( |
| 179 | + context, |
| 180 | + extensionId, |
| 181 | + "inject_content_test.js", |
| 182 | + TARGET_URL, |
| 183 | + 60_000 |
| 184 | + ); |
| 185 | + |
| 186 | + console.log(`[inject_content_test] passed=${passed}, failed=${failed}`); |
| 187 | + if (failed !== 0) { |
| 188 | + console.log("[inject_content_test] logs:", logs.join("\n")); |
| 189 | + } |
| 190 | + expect(failed, "Some content inject tests failed").toBe(0); |
| 191 | + expect(passed, "No test results found - script may not have run").toBeGreaterThan(0); |
| 192 | + }); |
| 193 | +}); |
0 commit comments