Files
COMERCIAL-GTI/tests/backup-data.test.mjs
T
2026-09-28 15:48:44 -03:00

71 lines
3.0 KiB
JavaScript

import test from 'node:test';
import assert from 'node:assert/strict';
import fs from 'node:fs/promises';
import os from 'node:os';
import path from 'node:path';
import { DatabaseSync } from 'node:sqlite';
import { createBackup, isCliEntryPoint } from '../scripts/backup-data.mjs';
test('backup creates data copy and keeps configured retention', async () => {
const tmp = await fs.mkdtemp(path.join(os.tmpdir(), 'mcp-backup-'));
const dataDir = path.join(tmp, 'data');
const backupsDir = path.join(dataDir, 'backups');
const authDir = path.join(dataDir, 'runtime', 'whatsapp-auth');
await fs.mkdir(authDir, { recursive: true });
await fs.mkdir(path.join(backupsDir, 'maquina-pessoal-2026-08-01'), { recursive: true });
await fs.mkdir(path.join(backupsDir, 'maquina-pessoal-2026-08-02'), { recursive: true });
await fs.writeFile(path.join(dataDir, 'maquina-pessoal.db'), 'db');
await fs.writeFile(path.join(authDir, 'session.json'), 'auth');
try {
const result = await createBackup({ dataDir, now: () => new Date('2026-08-03T10:00:00Z'), retention: 1 });
assert.match(result.file, /maquina-pessoal-2026-08-03$/);
assert.equal(await fs.readFile(path.join(result.file, 'maquina-pessoal.db'), 'utf8'), 'db');
assert.equal(await fs.readFile(path.join(result.file, 'whatsapp-auth', 'session.json'), 'utf8'), 'auth');
assert.deepEqual(await fs.readdir(backupsDir), ['maquina-pessoal-2026-08-03']);
} finally {
await fs.rm(tmp, { recursive: true, force: true });
}
});
test('CLI guard matches Windows file URLs from argv paths', () => {
assert.equal(
isCliEntryPoint('file:///D:/PROJETOS/COMERCIAL%20GTI/MAQUINA%20COMERCIAL%20PESSOAL/scripts/backup-data.mjs', 'D:\\PROJETOS\\COMERCIAL GTI\\MAQUINA COMERCIAL PESSOAL\\scripts\\backup-data.mjs'),
true
);
});
test('backup captures committed WAL data while source database remains open', async () => {
const tmp = await fs.mkdtemp(path.join(os.tmpdir(), 'mcp-backup-wal-'));
const dataDir = path.join(tmp, 'data');
const authDir = path.join(dataDir, 'runtime', 'whatsapp-auth');
const dbPath = path.join(dataDir, 'maquina-pessoal.db');
let db;
await fs.mkdir(authDir, { recursive: true });
await fs.writeFile(path.join(authDir, 'session.json'), 'auth');
try {
db = new DatabaseSync(dbPath);
db.exec('PRAGMA journal_mode = WAL;');
db.exec('CREATE TABLE records (id INTEGER PRIMARY KEY, name TEXT NOT NULL);');
db.exec("INSERT INTO records (name) VALUES ('committed in wal');");
await fs.stat(`${dbPath}-wal`);
const result = await createBackup({ dataDir, now: () => new Date('2026-08-03T10:00:00Z'), retention: 1 });
const backupDb = new DatabaseSync(path.join(result.file, 'maquina-pessoal.db'), { readOnly: true });
try {
assert.deepEqual(backupDb.prepare('SELECT name FROM records').all().map((row) => row.name), ['committed in wal']);
} finally {
backupDb.close();
}
} finally {
db?.close();
await fs.rm(tmp, { recursive: true, force: true });
}
});