playwright_e2e.cjs 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410
  1. const assert = require("node:assert/strict");
  2. const fs = require("node:fs");
  3. const path = require("node:path");
  4. const {chromium} = require(path.resolve(__dirname, "../../tools/board-viewer/node_modules/playwright"));
  5. const root = path.resolve(__dirname, "../..");
  6. const baseUrl = process.env.BOARD_VIEWER_URL || "http://127.0.0.1:8765";
  7. const origin = new URL(baseUrl).origin;
  8. const artifacts = process.env.BOARD_VIEWER_E2E_ARTIFACTS || path.resolve(process.env.TEMP || root, "board-viewer-e2e");
  9. const executablePath = process.env.BOARD_VIEWER_BROWSER || undefined;
  10. const launchArgs = String(process.env.BOARD_VIEWER_BROWSER_ARGS || "")
  11. .split(/\s+/)
  12. .filter(Boolean);
  13. if (launchArgs.length === 0 && process.platform === "linux") {
  14. launchArgs.push("--disable-gpu", "--disable-dev-shm-usage", "--no-sandbox");
  15. }
  16. const boardData = JSON.parse(fs.readFileSync(path.join(root, "tools/board-viewer/generated/board-data.json"), "utf8"));
  17. const candidateExpectation = JSON.parse(
  18. fs.readFileSync(path.join(root, "tests/board_viewer/fixtures/candidate_count_expectation.json"), "utf8"),
  19. );
  20. const expectedGpioCandidateCount = candidateExpectation.candidate_counts.gpio;
  21. const expectedHotspotCount = candidateExpectation.ui_counts?.touchpoints
  22. ?? boardData.touchpoints.length;
  23. const expectedPinCount = candidateExpectation.ui_counts?.pins
  24. ?? boardData.touchpoints.reduce((total, touchpoint) => total + (touchpoint.pins?.length ?? 0), 0);
  25. fs.mkdirSync(artifacts, {recursive: true});
  26. function clone(value) {
  27. return JSON.parse(JSON.stringify(value));
  28. }
  29. async function createPage(browser, viewport, options = {}) {
  30. const context = await browser.newContext({
  31. viewport,
  32. permissions: ["clipboard-read", "clipboard-write"],
  33. locale: "zh-CN",
  34. });
  35. const consoleErrors = [];
  36. const requestFailures = [];
  37. const badResponses = [];
  38. const page = await context.newPage();
  39. page.on("console", (message) => {
  40. if (message.type() === "error") consoleErrors.push(message.text());
  41. });
  42. page.on("requestfailed", (request) => requestFailures.push(`${request.url()}: ${request.failure()?.errorText}`));
  43. page.on("response", (response) => {
  44. if (response.status() >= 400) badResponses.push(`${response.status()} ${response.url()}`);
  45. });
  46. await page.route("**/*", async (route) => {
  47. const url = new URL(route.request().url());
  48. if (url.origin !== origin) {
  49. await route.abort("blockedbyclient");
  50. return;
  51. }
  52. if (options.data && url.pathname === "/generated/board-data.json") {
  53. await route.fulfill({status: 200, contentType: "application/json", body: JSON.stringify(options.data)});
  54. return;
  55. }
  56. if (options.runtime && url.pathname === "/api/status") {
  57. await route.fulfill({status: 200, contentType: "application/json", body: JSON.stringify(options.runtime)});
  58. return;
  59. }
  60. await route.continue();
  61. });
  62. await page.goto(baseUrl, {waitUntil: "networkidle"});
  63. await page.waitForFunction(
  64. (count) => document.querySelectorAll(".hotspot").length === count,
  65. expectedHotspotCount,
  66. );
  67. return {context, page, consoleErrors, requestFailures, badResponses};
  68. }
  69. async function assertHealthy(session) {
  70. await session.page.waitForTimeout(50);
  71. assert.deepEqual(session.consoleErrors, [], `console errors: ${session.consoleErrors.join("\n")}`);
  72. assert.deepEqual(session.requestFailures, [], `request failures: ${session.requestFailures.join("\n")}`);
  73. assert.deepEqual(session.badResponses, [], `bad responses: ${session.badResponses.join("\n")}`);
  74. }
  75. async function assertNoViewportOverflow(page) {
  76. const metrics = await page.evaluate(() => {
  77. const viewport = {width: window.innerWidth, height: window.innerHeight};
  78. const topbar = document.querySelector(".topbar").getBoundingClientRect();
  79. const board = document.querySelector(".board-pane").getBoundingClientRect();
  80. const boardViewport = document.querySelector("#board-viewport").getBoundingClientRect();
  81. const footer = document.querySelector(".board-footer").getBoundingClientRect();
  82. const panel = document.querySelector("#detail-panel").getBoundingClientRect();
  83. return {
  84. viewport,
  85. scrollWidth: document.documentElement.scrollWidth,
  86. scrollHeight: document.documentElement.scrollHeight,
  87. topbar: {left: topbar.left, right: topbar.right, top: topbar.top, bottom: topbar.bottom},
  88. board: {left: board.left, right: board.right, top: board.top, bottom: board.bottom},
  89. boardViewport: {top: boardViewport.top, bottom: boardViewport.bottom, height: boardViewport.height},
  90. footer: {top: footer.top, bottom: footer.bottom, height: footer.height},
  91. panel: {left: panel.left, right: panel.right, top: panel.top, bottom: panel.bottom},
  92. loadingDisplay: getComputedStyle(document.querySelector("#board-loading")).display,
  93. };
  94. });
  95. assert.ok(metrics.scrollWidth <= metrics.viewport.width + 1, JSON.stringify(metrics));
  96. assert.ok(metrics.scrollHeight <= metrics.viewport.height + 1, JSON.stringify(metrics));
  97. assert.ok(metrics.topbar.left >= -1 && metrics.topbar.right <= metrics.viewport.width + 1, JSON.stringify(metrics));
  98. assert.ok(metrics.board.left >= -1 && metrics.board.right <= metrics.viewport.width + 1, JSON.stringify(metrics));
  99. assert.ok(metrics.panel.left >= -1 && metrics.panel.right <= metrics.viewport.width + 1, JSON.stringify(metrics));
  100. assert.equal(metrics.loadingDisplay, "none", JSON.stringify(metrics));
  101. if (metrics.viewport.width > 860) {
  102. assert.ok(metrics.boardViewport.height > 400, JSON.stringify(metrics));
  103. assert.ok(metrics.footer.height <= 34, JSON.stringify(metrics));
  104. assert.ok(metrics.footer.bottom >= metrics.viewport.height - 1, JSON.stringify(metrics));
  105. }
  106. }
  107. async function selectSearchResult(page, query, expectedKey) {
  108. const search = page.locator("#board-search");
  109. await search.fill(query);
  110. const result = page.locator(".search-result").filter({hasText: expectedKey}).first();
  111. await result.waitFor({state: "visible"});
  112. await result.click();
  113. }
  114. async function connectorGrid(page) {
  115. return page.locator(".connector-grid-row").evaluateAll((rows) =>
  116. rows.map((row) => Array.from(row.querySelectorAll(".connector-contact")).map((pin) => pin.textContent.trim())),
  117. );
  118. }
  119. async function assertRenderedPinPositionsMatchGeneratedData(page) {
  120. const rendered = await page.locator(".pin-group").evaluateAll((groups) => Object.fromEntries(
  121. groups.map((group) => {
  122. const dot = group.querySelector(".pin-dot");
  123. return [group.dataset.pinId, {x: Number(dot.getAttribute("cx")), y: Number(dot.getAttribute("cy"))}];
  124. }),
  125. ));
  126. const expected = Object.fromEntries(boardData.touchpoints.flatMap((touchpoint) =>
  127. touchpoint.pins.map((pin) => [pin.id, pin.view_position]),
  128. ));
  129. assert.equal(Object.keys(rendered).length, expectedPinCount);
  130. assert.deepEqual(Object.keys(rendered).sort(), Object.keys(expected).sort());
  131. for (const [id, point] of Object.entries(expected)) {
  132. assert.ok(Math.abs(rendered[id].x - point.x) < 1e-9, `${id} x: ${rendered[id].x} != ${point.x}`);
  133. assert.ok(Math.abs(rendered[id].y - point.y) < 1e-9, `${id} y: ${rendered[id].y} != ${point.y}`);
  134. }
  135. }
  136. async function desktopWorkflow(browser, viewport, name) {
  137. const session = await createPage(browser, viewport);
  138. const {page} = session;
  139. try {
  140. await page.getByText("数据已校验", {exact: true}).waitFor();
  141. assert.equal(await page.locator(".hotspot").count(), expectedHotspotCount);
  142. assert.equal(await page.locator(".pin-group").count(), expectedPinCount);
  143. await assertRenderedPinPositionsMatchGeneratedData(page);
  144. assert.equal(await page.locator(".pin-group").first().getAttribute("tabindex"), "-1");
  145. assert.equal(await page.locator("#photo-layer").isDisabled(), true);
  146. assert.equal(await page.locator('#layer-controls input[value="copper"]').isChecked(), true);
  147. assert.equal(await page.locator("#layer-copper").isVisible(), true);
  148. assert.equal(await page.locator("#layer-mask").getAttribute("href"), "/generated/board-mask-edge.svg");
  149. await assertNoViewportOverflow(page);
  150. await page.screenshot({path: path.join(artifacts, `${name}-initial.png`), fullPage: true});
  151. const con18 = page.locator('.hotspot[data-reference="CON18"]');
  152. const con18Box = await con18.boundingBox();
  153. assert.ok(con18Box);
  154. const connectorPosition = {x: con18Box.width / 2, y: Math.min(1, con18Box.height / 4)};
  155. await con18.hover({position: connectorPosition});
  156. await page.getByRole("tooltip").getByText("CON18", {exact: true}).waitFor();
  157. await con18.click({position: connectorPosition});
  158. await page.locator(".detail-reference").getByText("CON18", {exact: true}).waitFor();
  159. await page.getByText("板正面接触针排列", {exact: true}).waitFor();
  160. await page.getByText("板正面俯视", {exact: false}).waitFor();
  161. await page.getByText("线缆端或对接面可能是镜像", {exact: false}).waitFor();
  162. assert.deepEqual(await connectorGrid(page), [
  163. ["13", "11", "9", "7", "5", "3", "1"],
  164. ["14", "12", "10", "8", "6", "4", "2"],
  165. ]);
  166. assert.equal(await page.locator('.pin-row[data-pad-role="contact"]').count(), 14);
  167. await page.getByText("上", {exact: true}).first().waitFor();
  168. await page.getByText("下", {exact: true}).first().waitFor();
  169. await selectSearchResult(page, "CON23", "CON23");
  170. assert.deepEqual(await connectorGrid(page), [["5", "1"], ["6", "2"], ["7", "3"], ["8", "4"]]);
  171. await selectSearchResult(page, "CON8", "CON8");
  172. assert.deepEqual(await connectorGrid(page), [["8"], ["7"], ["6"], ["5"], ["4"], ["3"], ["2"], ["1"]]);
  173. await selectSearchResult(page, "J3", "J3");
  174. await page.getByText("EF2L45BG256B FPGA JTAG 调试/配置接口(专用配置脚)", {exact: true}).waitFor();
  175. await page.locator(".category-tag").getByText("调试接口", {exact: true}).waitFor();
  176. assert.deepEqual(await connectorGrid(page), [
  177. ["1", "2"],
  178. ["3", "4"],
  179. ["5", "6"],
  180. ["7", "8"],
  181. ["9", "10"],
  182. ]);
  183. const j3Pin1Primary = await page.locator('.pin-row[data-pin="1"] .pin-primary > span').allTextContents();
  184. assert.match(j3Pin1Primary[0], /TCK/);
  185. assert.match(j3Pin1Primary[1], /原始网络.*N9532014/);
  186. await selectSearchResult(page, "J3.1", "J3.1");
  187. await page.getByText("FPGA 专用 JTAG 时钟输入", {exact: false}).first().waitFor();
  188. await page.getByText("U3.A7 专用 TCK", {exact: true}).waitFor();
  189. await page.getByText("R63 22R 串联", {exact: true}).first().waitFor();
  190. await page.getByText("不要在 RTL 顶层声明", {exact: false}).waitFor();
  191. await page.getByText("专用配置脚不使用用户 ADC 约束", {exact: true}).waitFor();
  192. assert.equal(await page.getByLabel("RTL 端口名").count(), 0);
  193. await page.screenshot({path: path.join(artifacts, `${name}-j3.png`), fullPage: true});
  194. await assertNoViewportOverflow(page);
  195. await selectSearchResult(page, "J3.4", "J3.4");
  196. await page.getByText("不是给板子供电", {exact: false}).first().waitFor();
  197. await page.getByText("R61 0R", {exact: false}).first().waitFor();
  198. await page.getByText("不要通过 VREF 反向给板子供电", {exact: false}).waitFor();
  199. await selectSearchResult(page, "J3.6", "J3.6");
  200. await page.getByText("不能把 NC 当作备用 GPIO", {exact: false}).waitFor();
  201. await selectSearchResult(page, "J11", "J11");
  202. await page.locator(".category-tag").getByText("安装孔", {exact: true}).waitFor();
  203. await page.getByText("M3 安装孔(非电气接口)", {exact: true}).waitFor();
  204. await selectSearchResult(page, "J8", "J8");
  205. await page.locator(".category-tag").getByText("制造标记", {exact: true}).waitFor();
  206. await selectSearchResult(page, "PL2001", "PL2001");
  207. await page.locator(".category-tag").getByText("电源器件", {exact: true}).waitFor();
  208. await page.getByText("+5V 开关电源电感(非连接器)", {exact: true}).waitFor();
  209. const beforeZoom = await page.locator("#board-svg").getAttribute("viewBox");
  210. await page.getByRole("button", {name: "放大"}).click();
  211. const afterZoom = await page.locator("#board-svg").getAttribute("viewBox");
  212. assert.notEqual(afterZoom, beforeZoom);
  213. await selectSearchResult(page, "CON78", "CON78");
  214. assert.equal(await page.locator('.pin-row[data-pad-role="contact"]').count(), 4);
  215. assert.equal(await page.locator('.pin-row[data-pad-role="shield"]').count(), 2);
  216. assert.equal(await page.locator('.pin-group[data-reference="CON78"][data-pin="5"]').getAttribute("data-pad-role"), "shield");
  217. await page.getByText("屏蔽固定焊盘", {exact: true}).first().waitFor();
  218. await selectSearchResult(page, "CON78.1", "CON78.1");
  219. assert.equal(await page.locator('.pin-group[data-reference="CON78"][data-pin="1"]').getAttribute("tabindex"), "0");
  220. await page.getByText("U23 TRSF3232EIPWR", {exact: true}).first().waitFor();
  221. await page.locator(".pin-detail .detail-facts").getByText("FPGA M10", {exact: true}).waitFor();
  222. await page.locator(".pin-detail").getByText("RS232_TX2", {exact: true}).first().waitFor();
  223. await page.getByText("编程结论", {exact: true}).waitFor();
  224. await page.getByText("FPGA 输出", {exact: false}).waitFor();
  225. await page.getByText("连接到对端设备的接收端(RX)。", {exact: true}).waitFor();
  226. await page.getByText("不能直接接 3.3V TTL/CMOS 串口", {exact: false}).waitFor();
  227. await page.getByText("LOCATION = M10", {exact: true}).waitFor();
  228. await page.getByText("IOSTANDARD = LVCMOS33", {exact: true}).waitFor();
  229. const groundPin = page.locator('.pin-group[data-reference="CON78"][data-pin="3"] .pin-hit');
  230. await groundPin.hover();
  231. await page.getByRole("tooltip").getByText("CON78.3", {exact: true}).waitFor();
  232. await groundPin.click();
  233. assert.ok(await page.locator(".net-highlight").count() > 20);
  234. await selectSearchResult(page, "CON12.3", "CON12.3");
  235. await page.getByText("FAN_GPIO1", {exact: false}).first().waitFor();
  236. await page.getByText("LOCATION = A11", {exact: true}).waitFor();
  237. await page.getByText("已验证直连 FPGA GPIO", {exact: false}).first().waitFor();
  238. await selectSearchResult(page, "CON31.4", "CON31.4");
  239. await page.getByText("开集电极", {exact: false}).first().waitFor();
  240. await page.getByText("FPGA high", {exact: false}).first().waitFor();
  241. await page.getByText("LOCATION = E10", {exact: true}).waitFor();
  242. await selectSearchResult(page, "CON54.1", "CON54.1");
  243. await page.getByText("open-drain", {exact: false}).first().waitFor();
  244. await page.getByText("开漏", {exact: false}).first().waitFor();
  245. await page.getByText("LOCATION = B14", {exact: true}).waitFor();
  246. await selectSearchResult(page, "CON53.1", "CON53.1");
  247. await page.getByText("远端温度二极管", {exact: false}).first().waitFor();
  248. await page.getByText("不要为 CON53.1 声明 FPGA GPIO", {exact: false}).waitFor();
  249. await selectSearchResult(page, "CON2.5", "CON2.5");
  250. await page.getByText("板端电源输入", {exact: false}).first().waitFor();
  251. await page.getByText("CON2.5 +12V_VIN", {exact: false}).first().waitFor();
  252. await selectSearchResult(page, "J25.2", "J25.2");
  253. await page.getByText("GD32F303CGT6", {exact: false}).first().waitFor();
  254. await page.getByText("SWCLK", {exact: false}).first().waitFor();
  255. await page.getByText("U27.37", {exact: false}).first().waitFor();
  256. await page.getByText("不对应 FPGA RTL 或 ADC", {exact: false}).waitFor();
  257. await page.locator("#candidate-tab").click();
  258. await page.locator("#capability-select").selectOption("pwm");
  259. const pwmCandidate = page.locator(".candidate-row").filter({hasText: "CON31.4 · E10"});
  260. await pwmCandidate.locator(".candidate-key").getByText("CON31.4 · E10", {exact: true}).waitFor();
  261. await pwmCandidate.getByText("FPGA high -> Q105", {exact: false}).waitFor();
  262. await page.locator("#capability-select").selectOption("gpio");
  263. assert.equal(await page.locator(".candidate-row").count(), expectedGpioCandidateCount);
  264. assert.equal(await page.locator(".candidate-row").filter({hasText: "CON31.4"}).count(), 0);
  265. await page.locator("#capability-select").selectOption("uart_tx");
  266. await page.getByText("没有满足全部证据条件的候选", {exact: true}).waitFor();
  267. await page.locator("#detail-tab").click();
  268. await page.locator("#board-search").fill("does-not-exist");
  269. await page.getByText("没有匹配的座子或针脚", {exact: true}).waitFor();
  270. await page.screenshot({path: path.join(artifacts, `${name}-selected.png`), fullPage: true});
  271. await assertNoViewportOverflow(page);
  272. await assertHealthy(session);
  273. } finally {
  274. await session.context.close();
  275. }
  276. }
  277. async function mobileWorkflow(browser) {
  278. const session = await createPage(browser, {width: 390, height: 844});
  279. const {page} = session;
  280. try {
  281. await assertNoViewportOverflow(page);
  282. await page.screenshot({path: path.join(artifacts, "390x844-initial.png"), fullPage: true});
  283. assert.equal(await page.locator("#app").evaluate((node) => node.classList.contains("detail-collapsed")), true);
  284. await selectSearchResult(page, "CON78", "CON78");
  285. assert.equal(await page.locator("#app").evaluate((node) => node.classList.contains("detail-collapsed")), false);
  286. await page.locator(".detail-reference").getByText("CON78", {exact: true}).waitFor();
  287. await page.screenshot({path: path.join(artifacts, "390x844-selected.png"), fullPage: true});
  288. await assertNoViewportOverflow(page);
  289. await selectSearchResult(page, "J3.1", "J3.1");
  290. await page.getByText("FPGA 专用 JTAG 时钟输入", {exact: false}).first().waitFor();
  291. await page.screenshot({path: path.join(artifacts, "390x844-j3.png"), fullPage: true});
  292. await assertNoViewportOverflow(page);
  293. await assertHealthy(session);
  294. } finally {
  295. await session.context.close();
  296. }
  297. }
  298. async function adcCopyWorkflow(browser) {
  299. const data = clone(boardData);
  300. const con78 = data.touchpoints.find((item) => item.reference === "CON78");
  301. const pin = con78.pins.find((item) => item.number === "1");
  302. pin.reserved = false;
  303. pin.recommendation = {eligible: true, reasons: ["capability_match", "verified_fpga_path", "external_level_known"]};
  304. const runtime = {
  305. status: "pass",
  306. staleSources: [],
  307. recommendationsEnabled: true,
  308. adcCopyEnabled: true,
  309. };
  310. const session = await createPage(browser, {width: 1366, height: 768}, {data, runtime});
  311. const {page} = session;
  312. try {
  313. await selectSearchResult(page, "CON78.1", "CON78.1");
  314. const input = page.getByLabel("RTL 端口名");
  315. assert.equal(await input.isEnabled(), true);
  316. await input.fill("uart2_tx");
  317. await page.getByRole("button", {name: "复制 ADC 片段"}).click();
  318. await page.getByText("ADC 片段已复制", {exact: true}).waitFor();
  319. const clipboard = await page.evaluate(() => navigator.clipboard.readText());
  320. assert.equal(clipboard, "set_pin_assignment { uart2_tx } { LOCATION = M10; IOSTANDARD = LVCMOS33; }");
  321. await assertHealthy(session);
  322. } finally {
  323. await session.context.close();
  324. }
  325. }
  326. async function staleWorkflow(browser) {
  327. const runtime = {
  328. status: "stale_sources",
  329. staleSources: ["sha256_mismatch:inventory"],
  330. recommendationsEnabled: false,
  331. adcCopyEnabled: false,
  332. };
  333. const session = await createPage(browser, {width: 1366, height: 768}, {runtime});
  334. const {page} = session;
  335. try {
  336. await page.getByText("来源已变化", {exact: true}).waitFor();
  337. await page.locator("#candidate-tab").click();
  338. await page.getByText("源文件状态不是当前值,选脚推荐已关闭。", {exact: true}).waitFor();
  339. await page.screenshot({path: path.join(artifacts, "stale-state.png"), fullPage: true});
  340. await assertHealthy(session);
  341. } finally {
  342. await session.context.close();
  343. }
  344. }
  345. (async () => {
  346. const launchOptions = {headless: true, args: launchArgs};
  347. if (executablePath) launchOptions.executablePath = executablePath;
  348. const browser = await chromium.launch(launchOptions);
  349. try {
  350. await desktopWorkflow(browser, {width: 1920, height: 1080}, "1920x1080");
  351. await desktopWorkflow(browser, {width: 1912, height: 948}, "1912x948");
  352. await mobileWorkflow(browser);
  353. await adcCopyWorkflow(browser);
  354. await staleWorkflow(browser);
  355. process.stdout.write(`Playwright board-viewer E2E passed. Artifacts: ${artifacts}\n`);
  356. } finally {
  357. await browser.close();
  358. }
  359. })().catch((error) => {
  360. console.error(error);
  361. process.exit(1);
  362. });