playwright_e2e.cjs 19 KB

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