fixtures.ts 10 KB

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