import { describe, it, beforeEach, afterEach } from 'node:test'; import assert from 'node:assert/strict'; import fs from 'fs'; import os from 'os'; import path from 'path'; import { validateJSONArrayFile, ensureJSONArrayFileExists } from './json.js'; describe('json helpers', () => { let workspace; beforeEach(() => { workspace = fs.mkdtempSync(path.join(os.tmpdir(), 'json-test-')); }); afterEach(() => { fs.rmSync(workspace, { recursive: true, force: true }); }); it('reports missing file without creating it', async () => { const fullPath = path.join(workspace, '.gitea/ai-review/findings.json'); const result = await validateJSONArrayFile(fullPath, '.gitea/ai-review/findings.json'); assert.deepEqual(result, { exists: false, valid: false, repaired: false }); assert.equal(fs.existsSync(fullPath), false); }); it('creates an empty array file when asked to ensure existence', () => { const fullPath = path.join(workspace, '.gitea/ai-review/findings.json'); const created = ensureJSONArrayFileExists(fullPath, '.gitea/ai-review/findings.json'); assert.equal(created, true); assert.equal(fs.readFileSync(fullPath, 'utf8'), '[]\n'); }); it('keeps a valid JSON array unchanged', async () => { const fullPath = path.join(workspace, '.gitea/ai-review/exclusions.json'); fs.mkdirSync(path.dirname(fullPath), { recursive: true }); fs.writeFileSync(fullPath, '[]\n', 'utf8'); const result = await validateJSONArrayFile(fullPath, '.gitea/ai-review/exclusions.json'); assert.deepEqual(result, { exists: true, valid: true, repaired: false }); assert.equal(fs.readFileSync(fullPath, 'utf8'), '[]\n'); }); it('repairs invalid JSON using AI output and rewrites the file', async () => { const fullPath = path.join(workspace, '.gitea/ai-review/findings.json'); fs.mkdirSync(path.dirname(fullPath), { recursive: true }); fs.writeFileSync(fullPath, '{broken', 'utf8'); const result = await validateJSONArrayFile(fullPath, '.gitea/ai-review/findings.json', async (_fullPath, _label, original) => { assert.equal(original, '{broken'); return '[{"fixed":true}]'; }); assert.deepEqual(result, { exists: true, valid: true, repaired: true }); assert.equal(fs.readFileSync(fullPath, 'utf8'), '[{"fixed":true}]\n'); }); });