pdf-preview.test.js 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504
  1. import { expect } from 'chai'
  2. import sinon from 'sinon'
  3. import fetchMock from 'fetch-mock'
  4. import { screen, fireEvent, waitFor, cleanup } from '@testing-library/react'
  5. import PdfPreview from '../../../../../frontend/js/features/pdf-preview/components/pdf-preview'
  6. import { renderWithEditorContext } from '../../../helpers/render-with-context'
  7. import nock from 'nock'
  8. import path from 'path'
  9. import fs from 'fs'
  10. import { cloneDeep } from 'lodash'
  11. const examplePDF = path.join(__dirname, '../fixtures/test-example.pdf')
  12. const corruptPDF = path.join(__dirname, '../fixtures/test-example-corrupt.pdf')
  13. const outputFiles = [
  14. {
  15. path: 'output.pdf',
  16. build: '123',
  17. url: '/build/output.pdf',
  18. type: 'pdf',
  19. },
  20. {
  21. path: 'output.bbl',
  22. build: '123',
  23. url: '/build/output.bbl',
  24. type: 'bbl',
  25. },
  26. {
  27. path: 'output.bib',
  28. build: '123',
  29. url: '/build/output.bib',
  30. type: 'bib',
  31. },
  32. {
  33. path: 'example.txt',
  34. build: '123',
  35. url: '/build/example.txt',
  36. type: 'txt',
  37. },
  38. {
  39. path: 'output.log',
  40. build: '123',
  41. url: '/build/output.log',
  42. type: 'log',
  43. },
  44. {
  45. path: 'output.blg',
  46. build: '123',
  47. url: '/build/output.blg',
  48. type: 'blg',
  49. },
  50. ]
  51. const mockCompile = () =>
  52. fetchMock.post('express:/project/:projectId/compile', {
  53. body: {
  54. status: 'success',
  55. clsiServerId: 'foo',
  56. compileGroup: 'priority',
  57. pdfDownloadDomain: '',
  58. outputFiles: cloneDeep(outputFiles),
  59. },
  60. })
  61. const mockCompileError = status =>
  62. fetchMock.post('express:/project/:projectId/compile', {
  63. body: {
  64. status,
  65. clsiServerId: 'foo',
  66. compileGroup: 'priority',
  67. },
  68. })
  69. const mockValidationProblems = validationProblems =>
  70. fetchMock.post('express:/project/:projectId/compile', {
  71. body: {
  72. status: 'validation-problems',
  73. validationProblems,
  74. clsiServerId: 'foo',
  75. compileGroup: 'priority',
  76. },
  77. })
  78. const mockClearCache = () =>
  79. fetchMock.delete('express:/project/:projectId/output', 204)
  80. const mockValidPdf = () => {
  81. nock('https://www.test-overleaf.com')
  82. .get(/^\/build\/output\.pdf/)
  83. .replyWithFile(200, examplePDF)
  84. }
  85. const defaultFileResponses = {
  86. '/build/output.pdf': () => fs.createReadStream(examplePDF),
  87. '/build/output.blg': 'This is BibTeX, Version 4.0', // FIXME
  88. '/build/output.log': `
  89. The LaTeX compiler output
  90. * With a lot of details
  91. Wrapped in an HTML <pre> element with
  92. preformatted text which is to be presented exactly
  93. as written in the HTML file
  94. (whitespace included™)
  95. The text is typically rendered using a non-proportional ("monospace") font.
  96. LaTeX Font Info: External font \`cmex10' loaded for size
  97. (Font) <7> on input line 18.
  98. LaTeX Font Info: External font \`cmex10' loaded for size
  99. (Font) <5> on input line 18.
  100. ! Undefined control sequence.
  101. <recently read> \\Zlpha
  102. main.tex, line 23
  103. `,
  104. }
  105. const mockBuildFile = (responses = defaultFileResponses) =>
  106. fetchMock.get('express:/build/:file', (_url, options, request) => {
  107. const url = new URL(_url, 'https://example.com')
  108. if (url.pathname in responses) {
  109. return responses[url.pathname]
  110. }
  111. return 404
  112. })
  113. const storeAndFireEvent = (key, value) => {
  114. localStorage.setItem(key, value)
  115. fireEvent(window, new StorageEvent('storage', { key }))
  116. }
  117. const scope = {
  118. settings: {
  119. syntaxValidation: false,
  120. },
  121. editor: {
  122. sharejs_doc: {
  123. doc_id: 'test-doc',
  124. getSnapshot: () => 'some doc content',
  125. },
  126. },
  127. }
  128. describe('<PdfPreview/>', function () {
  129. var clock
  130. beforeEach(function () {
  131. clock = sinon.useFakeTimers({
  132. shouldAdvanceTime: true,
  133. now: Date.now(),
  134. })
  135. nock.cleanAll()
  136. })
  137. afterEach(function () {
  138. clock.runAll()
  139. clock.restore()
  140. fetchMock.reset()
  141. localStorage.clear()
  142. sinon.restore()
  143. })
  144. it('renders the PDF preview', async function () {
  145. mockCompile()
  146. mockBuildFile()
  147. mockValidPdf()
  148. renderWithEditorContext(<PdfPreview />, { scope })
  149. // wait for "compile on load" to finish
  150. await screen.findByRole('button', { name: 'Compiling…' })
  151. await screen.findByRole('button', { name: 'Recompile' })
  152. })
  153. it('runs a compile when the Recompile button is pressed', async function () {
  154. mockCompile()
  155. mockBuildFile()
  156. mockValidPdf()
  157. renderWithEditorContext(<PdfPreview />, { scope })
  158. // wait for "compile on load" to finish
  159. await screen.findByRole('button', { name: 'Compiling…' })
  160. await screen.findByRole('button', { name: 'Recompile' })
  161. mockValidPdf()
  162. // press the Recompile button => compile
  163. const button = screen.getByRole('button', { name: 'Recompile' })
  164. button.click()
  165. await screen.findByRole('button', { name: 'Compiling…' })
  166. await screen.findByRole('button', { name: 'Recompile' })
  167. expect(fetchMock.calls()).to.have.length(6)
  168. })
  169. it('runs a compile on doc change if autocompile is enabled', async function () {
  170. mockCompile()
  171. mockBuildFile()
  172. mockValidPdf()
  173. renderWithEditorContext(<PdfPreview />, { scope })
  174. // wait for "compile on load" to finish
  175. await screen.findByRole('button', { name: 'Compiling…' })
  176. await screen.findByRole('button', { name: 'Recompile' })
  177. // switch on auto compile
  178. storeAndFireEvent('autocompile_enabled:project123', true)
  179. mockValidPdf()
  180. // fire a doc:changed event => compile
  181. fireEvent(window, new CustomEvent('doc:changed'))
  182. clock.tick(2000) // AUTO_COMPILE_DEBOUNCE
  183. await screen.findByRole('button', { name: 'Compiling…' })
  184. await screen.findByRole('button', { name: 'Recompile' })
  185. expect(fetchMock.calls()).to.have.length(6)
  186. })
  187. it('does not run a compile on doc change if autocompile is disabled', async function () {
  188. mockCompile()
  189. mockBuildFile()
  190. mockValidPdf()
  191. renderWithEditorContext(<PdfPreview />, { scope })
  192. // wait for "compile on load" to finish
  193. await screen.findByRole('button', { name: 'Compiling…' })
  194. await screen.findByRole('button', { name: 'Recompile' })
  195. // make sure auto compile is switched off
  196. storeAndFireEvent('autocompile_enabled:project123', false)
  197. // fire a doc:changed event => no compile
  198. fireEvent(window, new CustomEvent('doc:changed'))
  199. clock.tick(2000) // AUTO_COMPILE_DEBOUNCE
  200. screen.getByRole('button', { name: 'Recompile' })
  201. expect(fetchMock.calls()).to.have.length(3)
  202. })
  203. it('does not run a compile on doc change if autocompile is blocked by syntax check', async function () {
  204. mockCompile()
  205. mockBuildFile()
  206. mockValidPdf()
  207. renderWithEditorContext(<PdfPreview />, {
  208. scope: {
  209. ...scope,
  210. 'settings.syntaxValidation': true, // enable linting in the editor
  211. hasLintingError: true, // mock a linting error
  212. },
  213. })
  214. // wait for "compile on load" to finish
  215. await screen.findByRole('button', { name: 'Compiling…' })
  216. await screen.findByRole('button', { name: 'Recompile' })
  217. // switch on auto compile and syntax checking
  218. storeAndFireEvent('autocompile_enabled:project123', true)
  219. storeAndFireEvent('stop_on_validation_error:project123', true)
  220. // fire a doc:changed event => no compile
  221. fireEvent(window, new CustomEvent('doc:changed'))
  222. clock.tick(2000) // AUTO_COMPILE_DEBOUNCE
  223. screen.getByRole('button', { name: 'Recompile' })
  224. await screen.findByText('Code check failed')
  225. expect(fetchMock.calls()).to.have.length(3)
  226. })
  227. it('displays an error message if there was a compile error', async function () {
  228. const compileErrorStatuses = {
  229. 'clear-cache':
  230. 'Sorry, something went wrong and your project could not be compiled. Please try again in a few moments.',
  231. 'clsi-maintenance':
  232. 'The compile servers are down for maintenance, and will be back shortly.',
  233. 'compile-in-progress':
  234. 'A previous compile is still running. Please wait a minute and try compiling again.',
  235. exited: 'Server Error',
  236. failure: 'No PDF',
  237. generic: 'Server Error',
  238. 'project-too-large': 'Project too large',
  239. 'rate-limited': 'Compile rate limit hit',
  240. terminated: 'Compilation cancelled',
  241. timedout: 'Timed out',
  242. 'too-recently-compiled':
  243. 'This project was compiled very recently, so this compile has been skipped.',
  244. unavailable:
  245. 'Sorry, the compile server for your project was temporarily unavailable. Please try again in a few moments.',
  246. foo:
  247. 'Sorry, something went wrong and your project could not be compiled. Please try again in a few moments.',
  248. }
  249. for (const [status, message] of Object.entries(compileErrorStatuses)) {
  250. cleanup()
  251. fetchMock.restore()
  252. mockCompileError(status)
  253. renderWithEditorContext(<PdfPreview />, { scope })
  254. // wait for "compile on load" to finish
  255. await screen.findByRole('button', { name: 'Compiling…' })
  256. await screen.findByRole('button', { name: 'Recompile' })
  257. screen.getByText(message)
  258. }
  259. })
  260. it('displays expandable raw logs', async function () {
  261. mockCompile()
  262. mockBuildFile()
  263. mockValidPdf()
  264. // pretend that the content is large enough to trigger a "collapse"
  265. // (in jsdom these values are always zero)
  266. sinon.stub(HTMLElement.prototype, 'scrollHeight').value(500)
  267. sinon.stub(HTMLElement.prototype, 'scrollWidth').value(500)
  268. renderWithEditorContext(<PdfPreview />, { scope })
  269. // wait for "compile on load" to finish
  270. await screen.findByRole('button', { name: 'Compiling…' })
  271. await screen.findByRole('button', { name: 'Recompile' })
  272. const logsButton = screen.getByRole('button', { name: 'View logs' })
  273. logsButton.click()
  274. await screen.findByRole('button', { name: 'View PDF' })
  275. // expand the log
  276. const [expandButton] = screen.getAllByRole('button', { name: 'Expand' })
  277. expandButton.click()
  278. // collapse the log
  279. const [collapseButton] = screen.getAllByRole('button', { name: 'Collapse' })
  280. collapseButton.click()
  281. })
  282. it('displays error messages if there were validation problems', async function () {
  283. const validationProblems = {
  284. sizeCheck: {
  285. resources: [
  286. { path: 'foo/bar', kbSize: 76221 },
  287. { path: 'bar/baz', kbSize: 2342 },
  288. ],
  289. },
  290. mainFile: true,
  291. conflictedPaths: [
  292. {
  293. path: 'foo/bar',
  294. },
  295. {
  296. path: 'foo/baz',
  297. },
  298. ],
  299. }
  300. mockValidationProblems(validationProblems)
  301. renderWithEditorContext(<PdfPreview />, { scope })
  302. // wait for "compile on load" to finish
  303. await screen.findByRole('button', { name: 'Compiling…' })
  304. await screen.findByRole('button', { name: 'Recompile' })
  305. screen.getByText('Project too large')
  306. screen.getByText('Unknown main document')
  307. screen.getByText('Conflicting Paths Found')
  308. expect(fetchMock.called('express:/project/:projectId/compile')).to.be.true // TODO: auto_compile query param
  309. expect(fetchMock.called('express:/build/:file')).to.be.false // TODO: actual path
  310. })
  311. it('sends a clear cache request when the button is pressed', async function () {
  312. mockCompile()
  313. mockBuildFile()
  314. mockValidPdf()
  315. renderWithEditorContext(<PdfPreview />, { scope })
  316. // wait for "compile on load" to finish
  317. await screen.findByRole('button', { name: 'Compiling…' })
  318. await screen.findByRole('button', { name: 'Recompile' })
  319. const logsButton = screen.getByRole('button', {
  320. name: 'View logs',
  321. })
  322. logsButton.click()
  323. const clearCacheButton = await screen.findByRole('button', {
  324. name: 'Clear cached files',
  325. })
  326. expect(clearCacheButton.hasAttribute('disabled')).to.be.false
  327. mockClearCache()
  328. // click the button
  329. clearCacheButton.click()
  330. expect(clearCacheButton.hasAttribute('disabled')).to.be.true
  331. await waitFor(() => {
  332. expect(clearCacheButton.hasAttribute('disabled')).to.be.false
  333. })
  334. expect(fetchMock.called('express:/project/:projectId/compile')).to.be.true // TODO: auto_compile query param
  335. expect(fetchMock.called('express:/build/:file')).to.be.true // TODO: actual path
  336. })
  337. it('handle "recompile from scratch"', async function () {
  338. mockCompile()
  339. mockBuildFile()
  340. mockValidPdf()
  341. renderWithEditorContext(<PdfPreview />, { scope })
  342. // wait for "compile on load" to finish
  343. await screen.findByRole('button', { name: 'Compiling…' })
  344. await screen.findByRole('button', { name: 'Recompile' })
  345. // show the logs UI
  346. const logsButton = screen.getByRole('button', {
  347. name: 'View logs',
  348. })
  349. logsButton.click()
  350. const clearCacheButton = await screen.findByRole('button', {
  351. name: 'Clear cached files',
  352. })
  353. expect(clearCacheButton.hasAttribute('disabled')).to.be.false
  354. mockValidPdf()
  355. mockClearCache()
  356. const recompileFromScratch = screen.getByRole('menuitem', {
  357. name: 'Recompile from scratch',
  358. hidden: true,
  359. })
  360. recompileFromScratch.click()
  361. expect(clearCacheButton.hasAttribute('disabled')).to.be.true
  362. // wait for compile to finish
  363. await screen.findByRole('button', { name: 'Compiling…' })
  364. await screen.findByRole('button', { name: 'Recompile' })
  365. expect(fetchMock.called('express:/project/:projectId/compile')).to.be.true // TODO: auto_compile query param
  366. expect(fetchMock.called('express:/project/:projectId/output')).to.be.true
  367. expect(fetchMock.called('express:/build/:file')).to.be.true // TODO: actual path
  368. })
  369. it('shows an error for an invalid URL', async function () {
  370. mockCompile()
  371. mockBuildFile()
  372. nock('https://www.test-overleaf.com')
  373. .get(/^\/build\/output.pdf/)
  374. .replyWithError({
  375. message: 'something awful happened',
  376. code: 'AWFUL_ERROR',
  377. })
  378. const { rerender } = renderWithEditorContext(<PdfPreview />, { scope })
  379. await screen.findByText('Something went wrong while rendering this PDF.')
  380. expect(screen.queryByLabelText('Page 1')).to.not.exist
  381. mockValidPdf()
  382. rerender(<PdfPreview />)
  383. await screen.findByLabelText('Page 1')
  384. expect(screen.queryByText('Something went wrong while rendering this PDF.'))
  385. .to.not.exist
  386. })
  387. it('shows an error for a corrupt PDF', async function () {
  388. mockCompile()
  389. mockBuildFile()
  390. nock('https://www.test-overleaf.com')
  391. .get(/^\/build\/output.pdf/)
  392. .replyWithFile(200, corruptPDF)
  393. const { rerender } = renderWithEditorContext(<PdfPreview />, { scope })
  394. await screen.findByText('Something went wrong while rendering this PDF.')
  395. expect(screen.queryByLabelText('Page 1')).to.not.exist
  396. mockValidPdf()
  397. rerender(<PdfPreview />)
  398. await screen.findByLabelText('Page 1')
  399. expect(screen.queryByText('Something went wrong while rendering this PDF.'))
  400. .to.not.exist
  401. })
  402. })