Files
markdown-converter/tests/main/ImageOperations.test.js
T
amitwh cd0050d988 feat(recovery): autosave buffer + crash-recovery banner
VersionHistory snapshots the previous content on every explicit save — an
unsaved buffer is still lost on crash. AutosaveBuffer fills that gap.

- src/main/AutosaveBuffer.js — pure module mirroring VersionHistory's
  injectable-IO pattern; one blob per doc path under
  <userData>/autosave/by-path/<sha1>/recovery.md + meta.json. No history
  (VersionHistory owns that) — just the latest dirty buffer.
- src/main.js — IPC channels autosave:write/read/clear/list; real paths
  go through validatePath, synthetic 'untitled-tab-<id>' keys skip it.
- src/preload.js — added the four channels to ALLOWED_SEND_CHANNELS.
- src/renderer/autosave-client.js — debounced (2s) flush per tab +
  periodic safety net (10s max age) + dirty-write retry on failure.
- src/renderer.js — register on tab create, unregister on close,
  notifyChange piggybacks on performAutoSave's existing dirty-check,
  clearForDocPath after a successful save, showAutosaveRecoveryBanner
  on startup listing pending recoveries with Restore/Dismiss.

Tests (39 new):
- tests/main/AutosaveBuffer.test.js (19): round-trip, overwrite, isolation,
  unicode/emoji, empty content, null coercion, ENOENT vs corrupt meta,
  list ordering, corrupt-sibling skip, input validation, sha1 storage.
- tests/autosave-client.test.js (11): debounce, flushNow bypass,
  no-path skip, clearForDocPath, list proxy, IPC error fallback,
  unregister tear-down, failure-retry, periodic flush, idempotency.

Full suite: 692 tests pass, 63 suites, lint+format clean.

Amit Haridas
2026-09-14 00:00:16 +05:30

133 lines
4.8 KiB
JavaScript

const sharp = require('sharp');
const fs = require('fs');
const os = require('os');
const path = require('path');
const ImageOperations = require('../../src/main/ImageOperations');
describe('ImageOperations', () => {
let tmpDir, inputPath;
beforeEach(async () => {
tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'imgops_'));
inputPath = path.join(tmpDir, 'in.png');
await sharp({
create: { width: 100, height: 100, channels: 3, background: { r: 255, g: 0, b: 0 } },
})
.png()
.toFile(inputPath);
});
// Windows: sharp can hold the file handle briefly after await returns,
// so plain rmSync throws EPERM — retry and tolerate stale temp dirs.
afterEach(() => {
try {
fs.rmSync(tmpDir, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 });
} catch {
/* leftover temp dir is cosmetic on locked-file platforms */
}
});
test('imageConvert converts PNG to JPEG', async () => {
const outputPath = path.join(tmpDir, 'out.jpg');
const result = await ImageOperations.imageConvert({ inputPath, outputPath, format: 'jpeg' });
expect(result.success).toBe(true);
expect(fs.existsSync(outputPath)).toBe(true);
const meta = await sharp(outputPath).metadata();
expect(meta.format).toBe('jpeg');
});
test('imageResize resizes to given width preserving aspect', async () => {
const outputPath = path.join(tmpDir, 'out.png');
await ImageOperations.imageResize({
inputPath,
outputPath,
width: 50,
height: null,
fit: 'inside',
});
const meta = await sharp(outputPath).metadata();
expect(meta.width).toBe(50);
});
test('imageRotate rotates by given angle', async () => {
const outputPath = path.join(tmpDir, 'out.png');
await ImageOperations.imageRotate({ inputPath, outputPath, angle: 90 });
const meta = await sharp(outputPath).metadata();
expect(meta.width).toBe(100); // 90deg on square stays square
});
test('imageCompress produces a smaller or equal-size JPEG at low quality', async () => {
const jpegPath = path.join(tmpDir, 'in.jpg');
await sharp(inputPath).jpeg({ quality: 100 }).toFile(jpegPath);
const outputPath = path.join(tmpDir, 'compressed.jpg');
await ImageOperations.imageCompress({ inputPath: jpegPath, outputPath, quality: 10 });
expect(fs.statSync(outputPath).size).toBeLessThanOrEqual(fs.statSync(jpegPath).size);
});
test('executeOperation dispatches to the correct function', async () => {
const outputPath = path.join(tmpDir, 'out.png');
const result = await ImageOperations.executeOperation('rotate', {
inputPath,
outputPath,
angle: 180,
});
expect(result.success).toBe(true);
});
test('unknown operation throws', async () => {
await expect(ImageOperations.executeOperation('bogus', {})).rejects.toThrow();
});
});
describe('ImageOperations when sharp fails to load (boot resilience)', () => {
// Reproduces the packaged-deb crash: the native @img/sharp-* bindings are
// missing/pruned, so require('sharp') throws. Importing ImageOperations must
// never crash the app at boot, and every operation must degrade honestly.
const dlopenErrorMessage =
'Could not load the "sharp" module using the linux-x64 runtime. ' +
'ERR_DLOPEN_FAILED: libvips-cpp.so.8.17.3: cannot open shared object file ' +
'(searched /opt/MarkdownConverter/resources/app.asar.unpacked/node_modules/@img/' +
'sharp-linux-x64/lib, /opt/MarkdownConverter/resources/app.asar/node_modules/@img/' +
'sharp-linux-x64/lib, ...)';
let isolatedModule;
beforeEach(() => {
jest.resetModules();
jest.doMock('sharp', () => {
throw new Error(dlopenErrorMessage);
});
jest.isolateModules(() => {
isolatedModule = require('../../src/main/ImageOperations');
});
});
afterEach(() => {
jest.dontMock('sharp');
});
test('requiring ImageOperations does not throw at import time', () => {
expect(() => require('../../src/main/ImageOperations')).not.toThrow();
});
test("executeOperation('convert') resolves to an honest unavailable failure", async () => {
const result = await isolatedModule.executeOperation('convert', {
inputPath: '/tmp/imgops-resilience-in.png',
outputPath: '/tmp/imgops-resilience-out.jpg',
format: 'jpeg',
});
expect(result).toEqual({
success: false,
error: expect.stringContaining('Image operations unavailable'),
});
});
test('the unavailable failure message carries no absolute paths', async () => {
const result = await isolatedModule.executeOperation('rotate', {
inputPath: '/tmp/imgops-resilience-in.png',
outputPath: '/tmp/imgops-resilience-out.png',
angle: 90,
});
expect(result.success).toBe(false);
expect(result.error).not.toMatch(/\/opt\/|\/tmp\/|[A-Z]:\\/);
});
});