fixtures.ts 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312
  1. import * as fs from 'fs'
  2. import * as path from 'path'
  3. import { test as base, expect, ConsoleMessage, Locator } from '@playwright/test';
  4. import { ElectronApplication, Page, BrowserContext, _electron as electron } from 'playwright'
  5. import { loadLocalGraph, openLeftSidebar, randomString } from './utils';
  6. import { autocompleteMenu, LogseqFixtures } from './types';
  7. let electronApp: ElectronApplication
  8. let context: BrowserContext
  9. let page: Page
  10. let repoName = randomString(10)
  11. let testTmpDir = path.resolve(__dirname, '../tmp')
  12. if (fs.existsSync(testTmpDir)) {
  13. fs.rmSync(testTmpDir, { recursive: true })
  14. }
  15. export let graphDir = path.resolve(testTmpDir, "e2e-test", repoName)
  16. // NOTE: This following is a console log watcher for error logs.
  17. // Save and print all logs when error happens.
  18. let logs: string
  19. const consoleLogWatcher = (msg: ConsoleMessage) => {
  20. // console.log(msg.text())
  21. const text = msg.text()
  22. logs += text + '\n'
  23. // expect() will remember all arguments in memory,
  24. // and the memory usage will grow *exponentially* in the number of output line.
  25. // So we call expect() iff interesting pattern has already be found to avoid OOM.
  26. const expectNotMatchWithCheck = (pattern: RegExp) => {
  27. if (text.match(pattern)) {
  28. expect(text, logs).not.toMatch(pattern)
  29. }
  30. }
  31. expectNotMatchWithCheck(/^(Failed to|Uncaught)/)
  32. // youtube video
  33. // Error with Permissions-Policy header: Origin trial controlled feature not enabled: 'ch-ua-reduced'.
  34. if (!text.match(/^Error with Permissions-Policy header:/)) {
  35. expectNotMatchWithCheck(/^Error/)
  36. }
  37. // NOTE: React warnings will be logged as error.
  38. // expect(msg.type()).not.toBe('error')
  39. }
  40. base.beforeAll(async () => {
  41. if (electronApp) {
  42. return
  43. }
  44. console.log(`Creating test graph directory: ${graphDir}`)
  45. fs.mkdirSync(graphDir, {
  46. recursive: true,
  47. });
  48. electronApp = await electron.launch({
  49. cwd: "./static",
  50. args: ["electron.js"],
  51. locale: 'en',
  52. timeout: 10_000, // should be enough for the app to start
  53. })
  54. context = electronApp.context()
  55. await context.tracing.start({ screenshots: true, snapshots: true });
  56. await context.tracing.startChunk();
  57. // NOTE: The following ensures App first start with the correct path.
  58. const info = await electronApp.evaluate(async ({ app }) => {
  59. return {
  60. "appPath": app.getAppPath(),
  61. "appData": app.getPath("appData"),
  62. "userData": app.getPath("userData"),
  63. "appName": app.getName(),
  64. "electronVersion": app.getVersion(),
  65. }
  66. })
  67. console.log("Test start with:", info)
  68. page = await electronApp.firstWindow()
  69. // inject testing flags
  70. await page.evaluate(
  71. () => {
  72. Object.assign(window, {
  73. __E2E_TESTING__: true,
  74. })
  75. },
  76. )
  77. // Direct Electron console to watcher
  78. page.on('console', consoleLogWatcher)
  79. page.on('crash', () => {
  80. expect(false, "Page must not crash").toBeTruthy()
  81. })
  82. page.on('pageerror', (err) => {
  83. console.log(err)
  84. // expect(false, 'Page must not have errors!').toBeTruthy()
  85. })
  86. await page.waitForLoadState('domcontentloaded')
  87. // NOTE: The following ensures first start.
  88. // await page.waitForSelector('text=This is a demo graph, changes will not be saved until you open a local folder')
  89. await page.waitForSelector(':has-text("Loading")', {
  90. state: "hidden",
  91. timeout: 1000 * 15,
  92. });
  93. page.once('load', async () => {
  94. console.log('Page loaded!')
  95. await page.screenshot({ path: 'startup.png' })
  96. })
  97. await loadLocalGraph(page, graphDir);
  98. // render app
  99. await page.waitForFunction('window.document.title !== "Loading"')
  100. expect(await page.title()).toMatch(/^Logseq.*?/)
  101. await openLeftSidebar(page)
  102. })
  103. base.beforeEach(async () => {
  104. // discard any dialog by ESC
  105. if (page) {
  106. await page.keyboard.press('Escape')
  107. await page.keyboard.press('Escape')
  108. /*
  109. const locator = page.locator('.notification-close-button').first()
  110. while (await locator.isVisible()) {
  111. locator.click() // ignore error
  112. }
  113. */
  114. await expect(page.locator('.notification-close-button')).not.toBeVisible()
  115. const rightSidebar = page.locator('.cp__right-sidebar-inner')
  116. if (await rightSidebar.isVisible()) {
  117. await page.click('button.toggle-right-sidebar', {delay: 100})
  118. }
  119. }
  120. })
  121. // hijack electron app into the test context
  122. // FIXME: add type to `block`
  123. export const test = base.extend<LogseqFixtures>({
  124. page: async ({ }, use) => {
  125. await use(page);
  126. },
  127. // Timeout is used to avoid global timeout, local timeout will have a meaningful error report.
  128. // 1s timeout is enough for most of the test cases.
  129. // Timeout won't introduce additional sleeps.
  130. block: async ({ page }, use) => {
  131. const block = {
  132. mustFill: async (value: string) => {
  133. const locator: Locator = page.locator('textarea >> nth=0')
  134. await locator.waitFor({ timeout: 1000 })
  135. await locator.fill(value)
  136. await expect(locator).toHaveText(value, { timeout: 1000 })
  137. },
  138. mustType: async (value: string, options?: { delay?: number, toBe?: string }) => {
  139. const locator: Locator = page.locator('textarea >> nth=0')
  140. await locator.waitFor({ timeout: 1000 })
  141. const { delay = 50 } = options || {};
  142. const { toBe = value } = options || {};
  143. await locator.type(value, { delay })
  144. await expect(locator).toHaveText(toBe, { timeout: 1000 })
  145. },
  146. enterNext: async (): Promise<Locator> => {
  147. let blockCount = await page.locator('.page-blocks-inner .ls-block').count()
  148. await page.press('textarea >> nth=0', 'Enter')
  149. await page.waitForSelector(`.ls-block >> nth=${blockCount} >> textarea`, { state: 'visible', timeout: 1000 })
  150. return page.locator('textarea >> nth=0')
  151. },
  152. clickNext: async (): Promise<Locator> => {
  153. await page.$eval('.add-button-link-wrap', (element) => {
  154. element.scrollIntoView();
  155. });
  156. let blockCount = await page.locator('.page-blocks-inner .ls-block').count()
  157. // the next element after all blocks.
  158. await page.click('.add-button-link-wrap', { delay: 100 })
  159. await page.waitForSelector(`.ls-block >> nth=${blockCount} >> textarea`, { state: 'visible', timeout: 1000 })
  160. return page.locator('textarea >> nth=0')
  161. },
  162. indent: async (): Promise<boolean> => {
  163. const locator = page.locator('textarea >> nth=0')
  164. const before = await locator.boundingBox()
  165. await locator.press('Tab', { delay: 100 })
  166. return (await locator.boundingBox()).x > before.x
  167. },
  168. unindent: async (): Promise<boolean> => {
  169. const locator = page.locator('textarea >> nth=0')
  170. const before = await locator.boundingBox()
  171. await locator.press('Shift+Tab', { delay: 100 })
  172. return (await locator.boundingBox()).x < before.x
  173. },
  174. waitForBlocks: async (total: number): Promise<void> => {
  175. // NOTE: `nth=` counts from 0.
  176. await page.waitForSelector(`.ls-block >> nth=${total - 1}`, { state: 'attached', timeout: 50000 })
  177. await page.waitForSelector(`.ls-block >> nth=${total}`, { state: 'detached', timeout: 50000 })
  178. },
  179. waitForSelectedBlocks: async (total: number): Promise<void> => {
  180. // NOTE: `nth=` counts from 0.
  181. await page.waitForSelector(`.ls-block.selected >> nth=${total - 1}`, { timeout: 1000 })
  182. },
  183. escapeEditing: async (): Promise<void> => {
  184. const blockEdit = page.locator('.ls-block textarea >> nth=0')
  185. while (await blockEdit.isVisible()) {
  186. await page.keyboard.press('Escape')
  187. }
  188. const blockSelect = page.locator('.ls-block.selected')
  189. while (await blockSelect.isVisible()) {
  190. await page.keyboard.press('Escape')
  191. }
  192. },
  193. activeEditing: async (nth: number): Promise<void> => {
  194. await page.waitForSelector(`.ls-block >> nth=${nth}`, { timeout: 1000 })
  195. // scroll, for isVisible test
  196. await page.$eval(`.ls-block >> nth=${nth}`, (element) => {
  197. element.scrollIntoView();
  198. });
  199. // when blocks are nested, the first block(the parent) is selected.
  200. if (
  201. (await page.isVisible(`.ls-block >> nth=${nth} >> .editor-wrapper >> textarea`)) &&
  202. !(await page.isVisible(`.ls-block >> nth=${nth} >> .block-children-container >> textarea`))) {
  203. return;
  204. }
  205. await page.click(`.ls-block >> nth=${nth} >> .block-content`, { delay: 10, timeout: 100000 })
  206. await page.waitForSelector(`.ls-block >> nth=${nth} >> .editor-wrapper >> textarea`, { timeout: 1000, state: 'visible' })
  207. },
  208. isEditing: async (): Promise<boolean> => {
  209. const locator = page.locator('.ls-block textarea >> nth=0')
  210. return await locator.isVisible()
  211. },
  212. selectionStart: async (): Promise<number> => {
  213. return await page.locator('textarea >> nth=0').evaluate(node => {
  214. const elem = <HTMLTextAreaElement>node
  215. return elem.selectionStart
  216. })
  217. },
  218. selectionEnd: async (): Promise<number> => {
  219. return await page.locator('textarea >> nth=0').evaluate(node => {
  220. const elem = <HTMLTextAreaElement>node
  221. return elem.selectionEnd
  222. })
  223. }
  224. }
  225. use(block)
  226. },
  227. autocompleteMenu: async ({ }, use) => {
  228. const autocompleteMenu: autocompleteMenu = {
  229. expectVisible: async (modalName?: string) => {
  230. const modal = page.locator(modalName ? `[data-modal-name="${modalName}"]` : `[data-modal-name]`)
  231. if (await modal.isVisible()) {
  232. await page.waitForTimeout(100)
  233. await expect(modal).toBeVisible()
  234. } else {
  235. await modal.waitFor({ state: 'visible', timeout: 1000 })
  236. }
  237. },
  238. expectHidden: async (modalName?: string) => {
  239. const modal = page.locator(modalName ? `[data-modal-name="${modalName}"]` : `[data-modal-name]`)
  240. if (!await modal.isVisible()) {
  241. await page.waitForTimeout(100)
  242. await expect(modal).not.toBeVisible()
  243. } else {
  244. await modal.waitFor({ state: 'hidden', timeout: 1000 })
  245. }
  246. }
  247. }
  248. await use(autocompleteMenu)
  249. },
  250. context: async ({ }, use) => {
  251. await use(context);
  252. },
  253. app: async ({ }, use) => {
  254. await use(electronApp);
  255. },
  256. graphDir: async ({ }, use) => {
  257. await use(graphDir);
  258. },
  259. });
  260. let getTracingFilePath = function(): string {
  261. return `e2e-dump/trace-${Date.now()}.zip.dump`
  262. }
  263. test.afterAll(async () => {
  264. await context.tracing.stopChunk({ path: getTracingFilePath() });
  265. })
  266. /**
  267. * Trace all tests in a file
  268. */
  269. export let traceAll = function(){
  270. test.beforeAll(async () => {
  271. await context.tracing.startChunk();
  272. })
  273. test.afterAll(async () => {
  274. await context.tracing.stopChunk({ path: getTracingFilePath() });
  275. })
  276. }