Assessor_2.0/tests/importers/static-report-literal.test.ts

42 lines
2.6 KiB
TypeScript

import { describe, expect, it } from 'vitest';
import { assignedReportObjects, readStaticReportObject, STATIC_REPORT_LIMITS } from '../../src/importers/static-report-literal';
describe('inert static report data grammar', () => {
it('reads JSON and minified literal values without interpreting code', () => {
const source = '{ title: "a\\n\\u00e4\\x21", nested: [true,false,null,!0,!1,-2,1.2e3,], text: `line1\r\nline2`, quoted: \'it\\\'s safe\', }';
expect(readStaticReportObject(source, 0).value).toEqual({ title: 'a\nä!', nested: [true, false, null, true, false, -2, 1200], text: 'line1\nline2', quoted: "it's safe" });
});
it.each([
'{a: execute()}', '{a: externalValue}', '{a: external.value}', '{a: new Date()}',
'{get a(){return 1}}', '{["a"]:1}', '{...other}', '{a:`${execute()}`}',
'{a:1,a:2}', '{a:1+2}', '{a:NaN}', '{a:Infinity}', '{a:1e999}', '{a:undefined}',
'{a:()=>1}', '{a:1}.a', '{a:1}()', '{a:1} || other', '{a:[,1]}', '{a:"unterminated}',
'{a:"\\uZZZZ"}', '{a:"\\1"}', '{a:/* missing */}', '{a:01}', '{a:!2}', '{a:!0+1}'
])('rejects executable or ambiguous input: %s', source => {
expect(() => readStaticReportObject(source, 0)).toThrow(/static report data/);
});
it('preserves special keys as own inert data, without modifying prototypes', () => {
const parsed = readStaticReportObject('{"__proto__":{"polluted":true},constructor:"source"}', 0).value;
expect(Object.getPrototypeOf(parsed)).toBeNull();
expect(Object.hasOwn(parsed, '__proto__')).toBe(true);
expect(({} as Record<string, unknown>).polluted).toBeUndefined();
});
it('enforces nesting and string limits', () => {
expect(() => readStaticReportObject('{a:' + '['.repeat(STATIC_REPORT_LIMITS.depth + 1) + '0' + ']'.repeat(STATIC_REPORT_LIMITS.depth + 1) + '}', 0)).toThrow();
expect(() => readStaticReportObject('{a:"' + 'x'.repeat(STATIC_REPORT_LIMITS.string + 1) + '"}', 0)).toThrow();
});
it('ignores assignments inside strings, comments, templates and regular expressions', () => {
const script = 'const text="fake={Tests:[]}"; /* fake={Tests:[]} */ const re=/fake={Tests:[]}/; const template=`fake={Tests:[]} ${`nested fake={Tests:[]}`}`; const first=1, real={Tests:[]};';
expect([...assignedReportObjects(script)].map(item => item.binding)).toEqual(['real']);
});
it('bounds recursive template nesting while locating report assignments', () => {
const script = 'const ignored=' + '`\u0024{'.repeat(STATIC_REPORT_LIMITS.depth + 1) + '0' + '}`'.repeat(STATIC_REPORT_LIMITS.depth + 1);
expect(() => [...assignedReportObjects(script)]).toThrow(/nesting limit/);
});
});