pdf-preview.test.js 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507
  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: 'https://clsi.test-overleaf.com',
  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://clsi.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('begin:https://clsi.test-overleaf.com/', _url => {
  107. const url = new URL(_url, 'https://clsi.test-overleaf.com')
  108. if (url.pathname in responses) {
  109. return responses[url.pathname]
  110. }
  111. return 404
  112. })
  113. fetchMock.get('express:/build/:file', (_url, options, request) => {
  114. const url = new URL(_url, 'https://example.com')
  115. if (url.pathname in responses) {
  116. return responses[url.pathname]
  117. }
  118. return 404
  119. })
  120. }
  121. const storeAndFireEvent = (key, value) => {
  122. localStorage.setItem(key, value)
  123. fireEvent(window, new StorageEvent('storage', { key }))
  124. }
  125. const scope = {
  126. settings: {
  127. syntaxValidation: false,
  128. },
  129. editor: {
  130. sharejs_doc: {
  131. doc_id: 'test-doc',
  132. getSnapshot: () => 'some doc content',
  133. },
  134. },
  135. }
  136. describe('<PdfPreview/>', function () {
  137. let clock
  138. beforeEach(function () {
  139. window.showNewPdfPreview = true
  140. clock = sinon.useFakeTimers({
  141. shouldAdvanceTime: true,
  142. now: Date.now(),
  143. })
  144. nock.cleanAll()
  145. })
  146. afterEach(function () {
  147. window.showNewPdfPreview = undefined
  148. clock.runAll()
  149. clock.restore()
  150. fetchMock.reset()
  151. localStorage.clear()
  152. sinon.restore()
  153. })
  154. it('renders the PDF preview', async function () {
  155. mockCompile()
  156. mockBuildFile()
  157. mockValidPdf()
  158. renderWithEditorContext(<PdfPreview />, { scope })
  159. // wait for "compile on load" to finish
  160. await screen.findByRole('button', { name: 'Compiling…' })
  161. await screen.findByRole('button', { name: 'Recompile' })
  162. })
  163. it('runs a compile when the Recompile button is pressed', async function () {
  164. mockCompile()
  165. mockBuildFile()
  166. mockValidPdf()
  167. renderWithEditorContext(<PdfPreview />, { scope })
  168. // wait for "compile on load" to finish
  169. await screen.findByRole('button', { name: 'Compiling…' })
  170. await screen.findByRole('button', { name: 'Recompile' })
  171. mockValidPdf()
  172. // press the Recompile button => compile
  173. const button = screen.getByRole('button', { name: 'Recompile' })
  174. button.click()
  175. await screen.findByRole('button', { name: 'Compiling…' })
  176. await screen.findByRole('button', { name: 'Recompile' })
  177. expect(fetchMock.calls()).to.have.length(6)
  178. })
  179. it('runs a compile on doc change if autocompile is enabled', async function () {
  180. mockCompile()
  181. mockBuildFile()
  182. mockValidPdf()
  183. renderWithEditorContext(<PdfPreview />, { scope })
  184. // wait for "compile on load" to finish
  185. await screen.findByRole('button', { name: 'Compiling…' })
  186. await screen.findByRole('button', { name: 'Recompile' })
  187. // switch on auto compile
  188. storeAndFireEvent('autocompile_enabled:project123', true)
  189. mockValidPdf()
  190. // fire a doc:changed event => compile
  191. fireEvent(window, new CustomEvent('doc:changed'))
  192. clock.tick(2000) // AUTO_COMPILE_DEBOUNCE
  193. await screen.findByRole('button', { name: 'Compiling…' })
  194. await screen.findByRole('button', { name: 'Recompile' })
  195. expect(fetchMock.calls()).to.have.length(6)
  196. })
  197. it('does not run a compile on doc change if autocompile is disabled', async function () {
  198. mockCompile()
  199. mockBuildFile()
  200. mockValidPdf()
  201. renderWithEditorContext(<PdfPreview />, { scope })
  202. // wait for "compile on load" to finish
  203. await screen.findByRole('button', { name: 'Compiling…' })
  204. await screen.findByRole('button', { name: 'Recompile' })
  205. // make sure auto compile is switched off
  206. storeAndFireEvent('autocompile_enabled:project123', false)
  207. // fire a doc:changed event => no compile
  208. fireEvent(window, new CustomEvent('doc:changed'))
  209. clock.tick(2000) // AUTO_COMPILE_DEBOUNCE
  210. screen.getByRole('button', { name: 'Recompile' })
  211. expect(fetchMock.calls()).to.have.length(3)
  212. })
  213. it('does not run a compile on doc change if autocompile is blocked by syntax check', async function () {
  214. mockCompile()
  215. mockBuildFile()
  216. mockValidPdf()
  217. renderWithEditorContext(<PdfPreview />, {
  218. scope: {
  219. ...scope,
  220. 'settings.syntaxValidation': true, // enable linting in the editor
  221. hasLintingError: true, // mock a linting error
  222. },
  223. })
  224. // wait for "compile on load" to finish
  225. await screen.findByRole('button', { name: 'Compiling…' })
  226. await screen.findByRole('button', { name: 'Recompile' })
  227. // switch on auto compile and syntax checking
  228. storeAndFireEvent('autocompile_enabled:project123', true)
  229. storeAndFireEvent('stop_on_validation_error:project123', true)
  230. // fire a doc:changed event => no compile
  231. fireEvent(window, new CustomEvent('doc:changed'))
  232. clock.tick(2000) // AUTO_COMPILE_DEBOUNCE
  233. screen.getByRole('button', { name: 'Recompile' })
  234. await screen.findByText('Code check failed')
  235. expect(fetchMock.calls()).to.have.length(3)
  236. })
  237. describe('displays error messages', function () {
  238. const compileErrorStatuses = {
  239. 'clear-cache':
  240. 'Sorry, something went wrong and your project could not be compiled. Please try again in a few moments.',
  241. 'clsi-maintenance':
  242. 'The compile servers are down for maintenance, and will be back shortly.',
  243. 'compile-in-progress':
  244. 'A previous compile is still running. Please wait a minute and try compiling again.',
  245. exited: 'Server Error',
  246. failure: 'No PDF',
  247. generic: 'Server Error',
  248. 'project-too-large': 'Project too large',
  249. 'rate-limited': 'Compile rate limit hit',
  250. terminated: 'Compilation cancelled',
  251. timedout: 'Timed out',
  252. 'too-recently-compiled':
  253. 'This project was compiled very recently, so this compile has been skipped.',
  254. unavailable:
  255. 'Sorry, the compile server for your project was temporarily unavailable. Please try again in a few moments.',
  256. foo: 'Sorry, something went wrong and your project could not be compiled. Please try again in a few moments.',
  257. }
  258. for (const [status, message] of Object.entries(compileErrorStatuses)) {
  259. it(`displays error message for '${status}' status`, async function () {
  260. cleanup()
  261. fetchMock.restore()
  262. mockCompileError(status)
  263. renderWithEditorContext(<PdfPreview />, { scope })
  264. // wait for "compile on load" to finish
  265. await screen.findByRole('button', { name: 'Compiling…' })
  266. await screen.findByRole('button', { name: 'Recompile' })
  267. screen.getByText(message)
  268. })
  269. }
  270. })
  271. it('displays expandable raw logs', async function () {
  272. mockCompile()
  273. mockBuildFile()
  274. mockValidPdf()
  275. // pretend that the content is large enough to trigger a "collapse"
  276. // (in jsdom these values are always zero)
  277. sinon.stub(HTMLElement.prototype, 'scrollHeight').value(500)
  278. sinon.stub(HTMLElement.prototype, 'scrollWidth').value(500)
  279. renderWithEditorContext(<PdfPreview />, { scope })
  280. // wait for "compile on load" to finish
  281. await screen.findByRole('button', { name: 'Compiling…' })
  282. await screen.findByRole('button', { name: 'Recompile' })
  283. const logsButton = screen.getByRole('button', { name: 'View logs' })
  284. logsButton.click()
  285. await screen.findByRole('button', { name: 'View PDF' })
  286. // expand the log
  287. const [expandButton] = screen.getAllByRole('button', { name: 'Expand' })
  288. expandButton.click()
  289. // collapse the log
  290. const [collapseButton] = screen.getAllByRole('button', { name: 'Collapse' })
  291. collapseButton.click()
  292. })
  293. it('displays error messages if there were validation problems', async function () {
  294. const validationProblems = {
  295. sizeCheck: {
  296. resources: [
  297. { path: 'foo/bar', kbSize: 76221 },
  298. { path: 'bar/baz', kbSize: 2342 },
  299. ],
  300. },
  301. mainFile: true,
  302. conflictedPaths: [
  303. {
  304. path: 'foo/bar',
  305. },
  306. {
  307. path: 'foo/baz',
  308. },
  309. ],
  310. }
  311. mockValidationProblems(validationProblems)
  312. renderWithEditorContext(<PdfPreview />, { scope })
  313. // wait for "compile on load" to finish
  314. await screen.findByRole('button', { name: 'Compiling…' })
  315. await screen.findByRole('button', { name: 'Recompile' })
  316. screen.getByText('Project too large')
  317. screen.getByText('Unknown main document')
  318. screen.getByText('Conflicting Paths Found')
  319. expect(fetchMock.called('express:/project/:projectId/compile')).to.be.true // TODO: auto_compile query param
  320. expect(fetchMock.called('begin:https://clsi.test-overleaf.com/')).to.be
  321. .false // TODO: actual path
  322. })
  323. it('sends a clear cache request when the button is pressed', async function () {
  324. mockCompile()
  325. mockBuildFile()
  326. mockValidPdf()
  327. renderWithEditorContext(<PdfPreview />, { scope })
  328. // wait for "compile on load" to finish
  329. await screen.findByRole('button', { name: 'Compiling…' })
  330. await screen.findByRole('button', { name: 'Recompile' })
  331. const logsButton = screen.getByRole('button', {
  332. name: 'View logs',
  333. })
  334. logsButton.click()
  335. const clearCacheButton = await screen.findByRole('button', {
  336. name: 'Clear cached files',
  337. })
  338. expect(clearCacheButton.hasAttribute('disabled')).to.be.false
  339. mockClearCache()
  340. // click the button
  341. clearCacheButton.click()
  342. expect(clearCacheButton.hasAttribute('disabled')).to.be.true
  343. await waitFor(() => {
  344. expect(clearCacheButton.hasAttribute('disabled')).to.be.false
  345. })
  346. expect(fetchMock.called('express:/project/:projectId/compile')).to.be.true // TODO: auto_compile query param
  347. expect(fetchMock.called('begin:https://clsi.test-overleaf.com/')).to.be.true // TODO: actual path
  348. })
  349. it('handle "recompile from scratch"', async function () {
  350. mockCompile()
  351. mockBuildFile()
  352. mockValidPdf()
  353. renderWithEditorContext(<PdfPreview />, { scope })
  354. // wait for "compile on load" to finish
  355. await screen.findByRole('button', { name: 'Compiling…' })
  356. await screen.findByRole('button', { name: 'Recompile' })
  357. // show the logs UI
  358. const logsButton = screen.getByRole('button', {
  359. name: 'View logs',
  360. })
  361. logsButton.click()
  362. const clearCacheButton = await screen.findByRole('button', {
  363. name: 'Clear cached files',
  364. })
  365. expect(clearCacheButton.hasAttribute('disabled')).to.be.false
  366. mockValidPdf()
  367. mockClearCache()
  368. const recompileFromScratch = screen.getByRole('menuitem', {
  369. name: 'Recompile from scratch',
  370. hidden: true,
  371. })
  372. recompileFromScratch.click()
  373. expect(clearCacheButton.hasAttribute('disabled')).to.be.true
  374. // wait for compile to finish
  375. await screen.findByRole('button', { name: 'Compiling…' })
  376. await screen.findByRole('button', { name: 'Recompile' })
  377. expect(fetchMock.called('express:/project/:projectId/compile')).to.be.true // TODO: auto_compile query param
  378. expect(fetchMock.called('express:/project/:projectId/output')).to.be.true
  379. expect(fetchMock.called('begin:https://clsi.test-overleaf.com/')).to.be.true // TODO: actual path
  380. })
  381. it('shows an error for an invalid URL', async function () {
  382. mockCompile()
  383. mockBuildFile()
  384. nock('https://clsi.test-overleaf.com')
  385. .get(/^\/build\/output.pdf/)
  386. .replyWithError({
  387. message: 'something awful happened',
  388. code: 'AWFUL_ERROR',
  389. })
  390. renderWithEditorContext(<PdfPreview />, { scope })
  391. await screen.findByText('Something went wrong while rendering this PDF.')
  392. expect(screen.queryByLabelText('Page 1')).to.not.exist
  393. expect(nock.isDone()).to.be.true
  394. })
  395. it('shows an error for a corrupt PDF', async function () {
  396. mockCompile()
  397. mockBuildFile()
  398. nock('https://clsi.test-overleaf.com')
  399. .get(/^\/build\/output.pdf/)
  400. .replyWithFile(200, corruptPDF)
  401. renderWithEditorContext(<PdfPreview />, { scope })
  402. await screen.findByText('Something went wrong while rendering this PDF.')
  403. expect(screen.queryByLabelText('Page 1')).to.not.exist
  404. expect(nock.isDone()).to.be.true
  405. })
  406. })