fixtures.ts 10 KB

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