PdfToJpegConversionTests.js 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. import Client from './helpers/Client.js'
  2. import ClsiApp from './helpers/ClsiApp.js'
  3. import Path from 'node:path'
  4. import fs from 'node:fs/promises'
  5. import { promisify } from 'node:util'
  6. import { execFile as execFileCb } from 'node:child_process'
  7. import { expect } from 'chai'
  8. const execFile = promisify(execFileCb)
  9. const FIXTURE_PDF = Path.join(import.meta.dirname, '../fixtures/minimal.pdf')
  10. const MODE_EXPECTATIONS = {
  11. preview: { width: 794 },
  12. thumbnail: { width: 190 },
  13. }
  14. async function writeResponseToTempfile(response) {
  15. const buffer = Buffer.from(await response.arrayBuffer())
  16. const tmpPath = `/tmp/clsi-acceptance-pdf-to-jpeg-${crypto.randomUUID()}.jpg`
  17. await fs.writeFile(tmpPath, buffer)
  18. return { tmpPath, buffer }
  19. }
  20. describe('pdf-to-jpeg conversion', function () {
  21. before(async function () {
  22. await ClsiApp.ensureRunning()
  23. })
  24. for (const [mode, { width: expectedWidth }] of Object.entries(
  25. MODE_EXPECTATIONS
  26. )) {
  27. describe(`with mode=${mode}`, function () {
  28. let response
  29. let tmpPath
  30. let buffer
  31. before(async function () {
  32. response = await Client.convertPdfToJpeg(FIXTURE_PDF, mode)
  33. expect(response.status).to.equal(200)
  34. ;({ tmpPath, buffer } = await writeResponseToTempfile(response))
  35. })
  36. after(async function () {
  37. if (tmpPath) {
  38. await fs.unlink(tmpPath).catch(() => {})
  39. }
  40. })
  41. it('returns a JPEG (per `file`)', async function () {
  42. const { stdout } = await execFile('file', ['--brief', tmpPath])
  43. expect(stdout).to.match(/JPEG image data/)
  44. })
  45. it(`has the expected width of ${expectedWidth}px`, async function () {
  46. const { stdout } = await execFile('identify', [
  47. '-format',
  48. '%w %h',
  49. tmpPath,
  50. ])
  51. const [width, height] = stdout.trim().split(' ').map(Number)
  52. expect(width).to.equal(expectedWidth)
  53. // A4 portrait is taller than wide; height must be positive and
  54. // larger than the width (so the aspect ratio was preserved).
  55. expect(height).to.be.greaterThan(width)
  56. })
  57. it('returns a non-empty body matching Content-Length', function () {
  58. expect(buffer.length).to.be.greaterThan(0)
  59. expect(buffer.length).to.equal(
  60. Number(response.headers.get('content-length'))
  61. )
  62. })
  63. })
  64. }
  65. describe('with an unsupported mode', function () {
  66. it('returns 400', async function () {
  67. const response = await Client.convertPdfToJpeg(FIXTURE_PDF, 'not-a-mode')
  68. expect(response.status).to.equal(400)
  69. })
  70. })
  71. })