fixtures.ts 10 KB

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