Files
faunosteo/apps/app/tests/unit/scripts.compare.test.ts

349 lines
12 KiB
TypeScript

/**
* The archive check tool (scripts/compare-reports.ts) on the frozen v2 PDF,
* on a synthetic v2 report with removed and unknown items, on a v3 report
* and on a Step 6 envelope (archive header line).
*/
import { describe, it, expect, beforeAll } from 'vitest'
import { readFileSync } from 'node:fs'
import { fileURLToPath } from 'node:url'
import { dirname, resolve } from 'node:path'
import {
readArchiveDocument,
readReportDocument,
type ReportV2,
} from '@faunosteo/domain'
import { readAttachedDocument } from '@faunosteo/pdf'
import type { SheetIndex } from '@/services/sheetIndex'
import {
compareReport,
diffLines,
parseArgs,
renderComparison,
renderSummary,
UNRESOLVED,
} from '../../scripts/compare/report'
import { archiveEnvelope, loadTestSheet, minimalReport } from '../helpers/sheet'
const HERE = dirname(fileURLToPath(import.meta.url))
const OPTS = { locale: 'fr' as const, full: false }
let sheet: SheetIndex
function minimalV2(): ReportV2 {
return JSON.parse(
readFileSync(resolve(HERE, '../fixtures/report-v2.minimal.json'), 'utf8'),
) as ReportV2
}
function compareRaw(raw: unknown, full = false) {
const outcome = readArchiveDocument(raw, sheet.sheet.migrationMap)
return compareReport(raw, outcome, sheet, { ...OPTS, full })
}
beforeAll(async () => {
sheet = await loadTestSheet()
})
describe('compareReport on the frozen v2 archive PDF', () => {
it('shows every legacy zone and finding next to its canonical target', async () => {
const bytes = readFileSync(resolve(HERE, '../fixtures/report-v2.full.pdf'))
const raw = await readAttachedDocument(new Uint8Array(bytes))
const c = compareRaw(raw)
const lines = renderComparison('full.pdf', c)
expect(c.source).toBe('v2')
expect(lines[0]).toBe('== full.pdf')
expect(lines).toContain(' v2 → v3 (migrated)')
expect(lines.join('\n')).toContain(
'point-mpbwtst0 left "Hanche (coxo-fémorale)" → hip@main left "Hanche (coxo-fémorale)"',
)
expect(lines.join('\n')).toContain(
'cervical/cervical-observations/stumbling-proprioceptive (!) "Trébuchements / déficit proprioceptif rapporté" → cervical/cervical-consultation-reasons/stumbling-proprioceptive',
)
expect(lines.join('\n')).toContain('severity modérée → moderate')
expect(lines.some((l) => l.includes(UNRESOLVED))).toBe(false)
expect(c.counts).toEqual({
observations: 3,
zones: 5,
unresolvedZones: 0,
findings: 4,
unresolvedFindings: 0,
})
expect(renderSummary('full.pdf', c)).toBe(
'full.pdf · v2→v3 · 3 obs · zones 5/0 unresolved · findings 4/0 unresolved',
)
expect(lines.join('\n')).not.toContain('practitioner')
expect(lines.join('\n')).not.toContain('Dupont')
expect(renderComparison('x', compareRaw(raw, true)).join('\n')).toContain(
'practitioner "Dr. Claire Dupont"',
)
})
})
describe('compareReport on unresolved items', () => {
it('names a removed finding, a finding unknown to the catalog and an unknown zone', () => {
const v2: ReportV2 = {
...minimalV2(),
observations: [
{
id: 'o',
zones: [{ boneId: 'point-gone' }],
findings: [
{
zoneId: 'ssb',
path: ['ssb-dysfunctions', 'sutures', 'sphenozygomatic'],
labelFrSnapshot: 'Suture sphéno-zygomatique',
labelEnSnapshot: 'Sphenozygomatic suture',
requiresVetReferral: true,
},
{
zoneId: 'nowhere',
path: ['x'],
labelFrSnapshot: 'X',
labelEnSnapshot: 'X',
},
],
freeTextFindings: [],
comment: '',
},
],
}
const text = renderComparison('odd.pdf', compareRaw(v2)).join('\n')
expect(text).toContain(
`point-gone ${UNRESOLVED} unknown legacy id, kept as point-gone@main`,
)
expect(text).toContain(
`ssb/ssb-dysfunctions/sutures/sphenozygomatic (!) "Suture sphéno-zygomatique" ${UNRESOLVED} removed from the sheet, kept with its label`,
)
expect(text).toContain(
`nowhere/x "X" ${UNRESOLVED} never in the legacy catalog, kept with its label`,
)
expect(text).toContain('1 zones (1 unresolved) · 2 findings (2 unresolved)')
})
it('reads a v3 report as is and flags what the sheet cannot place', () => {
const report = minimalReport(sheet, {
observations: [
{
id: 'o3',
zones: [{ annotationId: 'hip', viewId: 'main', side: 'left' }],
findings: [
{
findingZoneId: 'hip',
path: ['hip-dysfunctions', 'articular', 'restriction-flexion'],
labelFrSnapshot: 'Restriction en flexion',
labelEnSnapshot: 'Flexion restriction',
},
{
findingZoneId: 'atm',
path: ['atm-observations', 'headshaking'],
labelFrSnapshot: 'Headshaking (secouement de tête)',
labelEnSnapshot: 'Headshaking',
unresolved: true,
},
{
findingZoneId: 'hip',
path: ['hip-dysfunctions'],
labelFrSnapshot: 'Catégorie',
labelEnSnapshot: 'Category',
},
],
freeTextFindings: [],
comment: '',
},
],
})
const c = compareRaw(report)
const text = renderComparison('v3.pdf', c).join('\n')
expect(c.source).toBe('v3')
expect(text).toContain('v3 (read as is)')
expect(text).toContain('hip@main left "Hanche (coxo-fémorale)"')
expect(text).toContain(
'hip/hip-dysfunctions/articular/restriction-flexion "Restriction en flexion"',
)
expect(text).toContain(
`atm/atm-observations/headshaking "Headshaking (secouement de tête)" ${UNRESOLVED} kept with its snapshot`,
)
expect(text).toContain('!! points at a category, not a leaf')
expect(c.counts.unresolvedFindings).toBe(1)
})
it('prints the archive line of an envelope: snapshot kept, or rejected with its reason', () => {
const envelope = archiveEnvelope(
sheet,
minimalReport(sheet, {
observations: [
{
id: 'o-env',
zones: [{ annotationId: 'hip', viewId: 'main', side: 'left' }],
findings: [],
freeTextFindings: [],
comment: '',
},
],
}),
)
const kept = compareRaw(envelope)
expect(kept.source).toBe('v3')
expect(kept.header).toContain('archive v1 (snapshot kept)')
const text = renderComparison('env.pdf', kept).join('\n')
expect(text).toContain('hip@main left "Hanche (coxo-fémorale)"')
const rejected = compareRaw({ ...envelope, envelopeVersion: 2 })
expect(rejected.header).toContain(
'archive v1 (snapshot rejected: unsupported_envelope)',
)
expect(compareRaw(envelope.report).header).not.toContain(
'archive v1 (snapshot kept)',
)
})
it('warns when a v3 report was written on another sheet document', () => {
const report = minimalReport(sheet, {
sheet: { ...sheet.sheet.ref, documentSha256: 'b'.repeat(64) },
})
const text = renderComparison('other.pdf', compareRaw(report)).join('\n')
expect(text).toContain(
'!! written on another sheet document (sha bbbbbbbbbbbb…)',
)
})
})
describe('diff and arguments', () => {
it('diffs the v3 content of a migrated v2 report and its v3 re-reading', () => {
const v2 = minimalV2()
const migrated = readReportDocument(v2, sheet.sheet.migrationMap).report
const a = compareRaw(v2)
const b = compareRaw(migrated)
expect(diffLines(a.normalized, b.normalized)).toEqual([])
const added = { ...migrated, conclusion: 'changed' }
expect(diffLines(a.normalized, compareRaw(added).normalized)).toEqual([
'+ conclusion (present)',
])
})
it('compares placeholders by default and real texts with --full', () => {
const base = readReportDocument(minimalV2(), sheet.sheet.migrationMap)
const original = { ...base.report, conclusion: 'original' }
const edited = { ...base.report, conclusion: 'changed' }
expect(
diffLines(compareRaw(original).normalized, compareRaw(edited).normalized),
).toEqual([])
expect(
diffLines(
compareRaw(original, true).normalized,
compareRaw(edited, true).normalized,
),
).toEqual(['- conclusion "original"', '+ conclusion "changed"'])
})
it('parses files and options, refuses unknown ones', () => {
expect(parseArgs(['a.pdf', '--summary', 'dir', '--locale', 'en'])).toEqual({
files: ['a.pdf', 'dir'],
locale: 'en',
full: false,
summary: true,
diff: false,
})
expect(parseArgs(['--full', '--diff', 'a', 'b']).full).toBe(true)
expect(() => parseArgs(['--identity'])).toThrow('unknown option')
expect(() => parseArgs(['--locale', 'de'])).toThrow('fr or en')
expect(() => parseArgs(['--json'])).toThrow('unknown option')
})
})
describe('terminal safety and privacy', () => {
const ESC = '\u001b[2K'
it('escapes control characters in every untrusted string', () => {
const report = minimalReport(sheet, {
observations: [
{
id: `o${ESC}\n1`,
zones: [],
findings: [
{
findingZoneId: 'hip',
path: ['hip-dysfunctions', `x${ESC}\ny`],
labelFrSnapshot: `L${ESC}`,
labelEnSnapshot: 'L',
unresolved: true,
},
],
freeTextFindings: [`t${ESC}\nu`],
comment: `c${ESC}\nd\u009b\u202e\u2028`,
},
],
})
const lines = renderComparison('x', compareRaw(report, true))
const text = lines.join('\n')
expect(text).not.toContain('\u001b')
expect(lines.every((l) => !l.includes('\n'))).toBe(true)
expect(text).toContain('\\u001b')
expect(text).toContain('\\u000a')
expect(text).toContain('[o\\u001b[2K\\u000a1]')
for (const raw of ['\u009b', '\u202e', '\u2028']) {
expect(text).not.toContain(raw)
}
for (const escaped of ['\\u009b', '\\u202e', '\\u2028']) {
expect(text).toContain(escaped)
}
})
it('does not throw on prototype-chain names used as legacy ids', () => {
const v2: ReportV2 = {
...minimalV2(),
observations: [
{
id: 'o',
zones: [{ boneId: '__proto__' }, { boneId: 'constructor' }],
findings: [
{
zoneId: '__proto__',
path: ['constructor'],
labelFrSnapshot: 'X',
labelEnSnapshot: 'X',
},
],
freeTextFindings: [],
comment: '',
},
],
}
const text = renderComparison('p.pdf', compareRaw(v2)).join('\n')
expect(text).toContain(`__proto__ ${UNRESOLVED}`)
expect(text).toContain(`constructor ${UNRESOLVED}`)
expect(text).toContain(`__proto__/constructor "X" ${UNRESOLVED}`)
})
it('hides names and free texts by default, shows them with --full', () => {
const report = minimalReport(sheet, {
conclusion: 'SECRET-CONCLUSION',
recommendations: 'SECRET-RECO',
nextAppointment: { kind: 'period', text: 'SECRET-WHEN' },
observations: [
{
id: 'o',
zones: [],
findings: [],
freeTextFindings: ['SECRET-TEXT'],
comment: 'SECRET-COMMENT',
},
],
})
const hidden = renderComparison('x', compareRaw(report)).join('\n')
expect(hidden).not.toContain('SECRET')
expect(hidden).toContain('text (1 entries)')
expect(hidden).toContain('comment (present)')
expect(hidden).toContain('conclusion (present)')
expect(hidden).toContain('recommendations (present)')
expect(hidden).toContain('next appointment (period)')
const shown = renderComparison('x', compareRaw(report, true)).join('\n')
for (const word of ['TEXT', 'COMMENT', 'CONCLUSION', 'RECO', 'WHEN']) {
expect(shown).toContain(`SECRET-${word}`)
}
expect(compareRaw(report).normalized.join('\n')).not.toContain('SECRET')
expect(compareRaw(report, true).normalized.join('\n')).toContain(
'SECRET-CONCLUSION',
)
})
})