fixtures.ts 10 KB

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