fixtures.ts 10 KB

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