import { assert } from "chai" import ValidationCompiler, { toRangeBound } from "../src/answers/ValidationCompiler" /** Compiles a single validation and runs it against an answer */ function check(validation: any, answer: any) { return new ValidationCompiler("en").compileValidations([validation])(answer) } /** Range validation with the given bounds and a message */ function range(literal: any) { return { op: "range", rhs: { literal }, message: { _base: "en", en: "Out of range" } } } /** Length range validation with the given bounds and a message */ function lengthRange(literal: any) { return { op: "lengthRange", rhs: { literal }, message: { _base: "en", en: "Bad length" } } } describe("ValidationCompiler", function () { describe("range", function () { it("passes a value within numeric bounds", function () { assert.isNull(check(range({ min: 1, max: 10 }), { value: 5 })) }) it("fails values outside numeric bounds", function () { assert.equal(check(range({ min: 1, max: 10 }), { value: 0 }), "Out of range") assert.equal(check(range({ min: 1, max: 10 }), { value: 11 }), "Out of range") }) it("compares string bounds numerically", function () { // "9" < "10" is false as strings, so this proves numeric comparison assert.isNull(check(range({ min: "9", max: "100" }), { value: 10 })) assert.equal(check(range({ min: "9", max: "100" }), { value: 101 }), "Out of range") assert.equal(check(range({ min: "0.5" }), { value: 0.25 }), "Out of range") }) it("treats an empty string bound as no bound", function () { assert.isNull(check(range({ min: "", max: "" }), { value: -5 })) assert.isNull(check(range({ min: "", max: "" }), { value: 500 })) }) it("never fails on an unparseable bound", function () { assert.isNull(check(range({ min: "15-20", max: "20-25" }), { value: 100 })) }) it("uses the quantity of a units answer", function () { assert.equal(check(range({ max: "10" }), { value: { quantity: 11, units: "m" } }), "Out of range") }) it("ignores a missing answer", function () { assert.isNull(check(range({ min: 1 }), { value: null })) }) }) describe("lengthRange", function () { it("checks length against string bounds numerically", function () { assert.isNull(check(lengthRange({ min: "2", max: "10" }), { value: "abcde" })) assert.equal(check(lengthRange({ min: "2", max: "10" }), { value: "a" }), "Bad length") assert.equal(check(lengthRange({ min: "2", max: "10" }), { value: "abcdefghijk" }), "Bad length") }) it("treats an empty string bound as no bound", function () { assert.isNull(check(lengthRange({ min: "", max: "" }), { value: "abcdefghijk" })) }) }) describe("toRangeBound", function () { it("converts bounds", function () { assert.isNull(toRangeBound(undefined)) assert.isNull(toRangeBound(null)) assert.isNull(toRangeBound(" ")) assert.equal(toRangeBound(3), 3) assert.equal(toRangeBound("3.5"), 3.5) assert.isTrue(Number.isNaN(toRangeBound("1,5"))) }) }) })