Files
DeepTutor/web/tests/numeric-answer.spec.ts
Benjamin Schwing 702b4854d1 fix(learning): harden numeric answer parsing
Review follow-ups for numeric_equivalent and its web port:

- Limit exponents to two digits; "1.5e10000000" made Fraction
  arithmetic block the event loop for about a minute.
- Treat a separator convention borrowed from the key as a preference,
  not a proof: "-12.500" for "-12500.00" is now ambiguous instead of a
  final "incorrect", since a comma-decimal learner may mean -12500.
- Accept "50%" for a bare "50" key, and two or more decimals that round
  to a fraction key ("0.333" for "1/3").
- Allow at most one trailing unit word; prose ("5 or six"), symbols
  ("3²"), single letters and magnitude words ("Tausend") are no longer
  dropped. Reject repeated signs ("--5").
- Use an absolute epsilon so large integer keys stay exact.
- Align Python and TS on ASCII digits, Unicode spaces and lower().

Signed-off-by: Benjamin Schwing <63053132+BenjiAvH@users.noreply.github.com>
2026-11-24 18:38:58 +00:00

57 lines
1.8 KiB
TypeScript

import { readFileSync } from 'node:fs'
import path from 'node:path'
import { describe, expect, it } from 'vitest'
import { numericEquivalent } from '@/lib/numeric-answer'
interface Vector {
user: string
expected: string
comparable: boolean
correct: boolean
ambiguous?: boolean
}
// Shared with deeptutor/learning/tests/test_grading.py so both ports agree.
const { vectors } = JSON.parse(
readFileSync(path.resolve(process.cwd(), '../tests/fixtures/numeric_answers.json'), 'utf8')
) as { vectors: Vector[] }
describe('numericEquivalent shared vectors', () => {
it.each(vectors)('$user ~ $expected', vector => {
const result = numericEquivalent(vector.user, vector.expected)
expect({
comparable: result.comparable,
correct: result.correct,
ambiguous: result.ambiguous,
}).toEqual({
comparable: vector.comparable,
correct: vector.correct,
ambiguous: vector.ambiguous ?? false,
})
})
})
describe('numericEquivalent', () => {
it('reports each labelled part', () => {
const result = numericEquivalent('b) 3,6; a) 12', 'a) 12; b) 3,5')
expect(result.parts.map(p => [p.label, p.correct])).toEqual([
['a', true],
['b', false],
])
})
it('lets explicit tolerances replace the key precision', () => {
expect(numericEquivalent('101', '100').correct).toBe(false)
expect(numericEquivalent('101', '100', { relTol: 0.01 }).correct).toBe(true)
expect(numericEquivalent('3.49', '3.48', { absTol: 0.02 }).correct).toBe(true)
expect(numericEquivalent('3.51', '3.48', { absTol: 0.02 }).correct).toBe(false)
})
})
describe('numericEquivalent units', () => {
it('does not treat object prototype keys as currencies', () => {
expect(numericEquivalent('5 constructor', '5 units').comparable).toBe(false)
})
})