forge
Explore
Log in

Don't you dare go Hollow

hezarfen_frontend

Clone
★ 0

0 watching0 forksTypeScript5.5 MiBdcf123aBurak Boduroğlu2 months ago674 commits

choice-set.property.test.ts176 lines, 7.4 KiBHistoryRawDownload
1import fc from "fast-check";
2import { expect, test } from "vitest";
3import {
4 addChoice,
5 blankChoiceSet,
6 type ChoiceSet,
7 moveChoice,
8 removeChoice,
9 setChoiceImage,
10 setChoiceText,
11 setCorrect,
12 storedChoiceSet,
13 submitChoices,
14} from "./choice-set";
15
16/**
17 * The example tests pin down seven known edits. These generate the edits
18 * instead, because every bug this reducer exists to kill lived in a *relation*
19 * between values — a row, its picture, the answer key, a student's answer —
20 * and an example can only re-assert the author's own mental model of it.
21 *
22 * The one invariant, restated: anything attached to a row (text, picture, the
23 * correct mark) stays attached to that row's id across any sequence of edits.
24 */
25
26const BASE32 = "0123456789ABCDEFGHJKMNPQRSTVWXYZ";
27const ulidArb = fc
28 .array(fc.constantFrom(...BASE32.split("")), { minLength: 26, maxLength: 26 })
29 .map((chars) => chars.join(""));
30
31/** Blank, whitespace-only, duplicated and arbitrary texts all matter here. */
32const textArb = fc.oneof(
33 fc.constant(""),
34 fc.constant(" "),
35 fc.constant("dup"),
36 fc.string({ maxLength: 8 }),
37);
38
39let stamped = 0;
40const stampFile = () => ({ name: `f${(stamped += 1)}` }) as unknown as File;
41
42type Op =
43 | { t: "add" }
44 | { t: "remove"; p: number }
45 | { t: "move"; p: number; q: number }
46 | { t: "text"; p: number; text: string }
47 | { t: "image"; p: number; keep: boolean }
48 | { t: "correct"; p: number }
49 | { t: "correctUnknown"; id: string };
50
51const pick = fc.double({ min: 0, max: 0.999, noNaN: true });
52const opArb: fc.Arbitrary<Op> = fc.oneof(
53 fc.constant<Op>({ t: "add" }),
54 fc.record({ t: fc.constant<"remove">("remove"), p: pick }),
55 fc.record({ t: fc.constant<"move">("move"), p: pick, q: pick }),
56 fc.record({ t: fc.constant<"text">("text"), p: pick, text: textArb }),
57 fc.record({ t: fc.constant<"image">("image"), p: pick, keep: fc.boolean() }),
58 fc.record({ t: fc.constant<"correct">("correct"), p: pick }),
59 fc.record({ t: fc.constant<"correctUnknown">("correctUnknown"), id: fc.oneof(ulidArb, fc.constant("new:0")) }),
60);
61
62/** Starting points: fresh forms, stored questions, empty sets, sets at max. */
63const startArb = fc.integer({ min: 2, max: 10 }).chain((max) =>
64 fc.oneof(
65 fc.integer({ min: 0, max }).map((n) => ({ max, set: blankChoiceSet(n) })),
66 fc
67 .uniqueArray(fc.record({ id: ulidArb, text: textArb }), { maxLength: max, selector: (c) => c.id })
68 .chain((choices) =>
69 (choices.length ? fc.option(fc.constantFrom(...choices.map((c) => c.id)), { nil: null }) : fc.constant(null))
70 .map((correct) => ({ max, set: storedChoiceSet(choices, correct) })),
71 ),
72 ),
73);
74
75const ids = (set: ChoiceSet) => set.rows.map((row) => row.id);
76const at = (set: ChoiceSet, p: number) => (set.rows.length ? set.rows[Math.floor(p * set.rows.length)].id : "absent");
77
78/** Apply one op and return it plus the id it was allowed to touch (if any). */
79function apply(set: ChoiceSet, op: Op, max: number): { next: ChoiceSet; touched: string | null } {
80 switch (op.t) {
81 case "add":
82 return { next: addChoice(set, max), touched: null };
83 case "remove":
84 return { next: removeChoice(set, at(set, op.p)), touched: at(set, op.p) };
85 case "move":
86 return { next: moveChoice(set, at(set, op.p), Math.floor(op.q * Math.max(set.rows.length, 1))), touched: null };
87 case "text":
88 return { next: setChoiceText(set, at(set, op.p), op.text), touched: at(set, op.p) };
89 case "image":
90 return { next: setChoiceImage(set, at(set, op.p), op.keep ? stampFile() : null), touched: at(set, op.p) };
91 case "correct":
92 return { next: setCorrect(set, at(set, op.p)), touched: null };
93 case "correctUnknown":
94 return { next: setCorrect(set, op.id), touched: null };
95 }
96}
97
98test("every edit sequence keeps text, picture and answer key attached to their row id", () => {
99 fc.assert(
100 fc.property(startArb, fc.array(opArb, { maxLength: 25 }), ({ max, set: start }, ops) => {
101 let set = start;
102 for (const op of ops) {
103 const before = set;
104 const { next, touched } = apply(set, op, max);
105 set = next;
106
107 // Ids are unique at all times, and the row count never exceeds max.
108 expect(new Set(ids(set)).size).toBe(set.rows.length);
109 expect(set.rows.length).toBeLessThanOrEqual(max);
110
111 // No op invents or duplicates an id: add appends exactly one new id,
112 // remove drops exactly the targeted one, everything else permutes.
113 const gained = ids(set).filter((id) => !ids(before).includes(id));
114 const lost = ids(before).filter((id) => !ids(set).includes(id));
115 expect(gained.length).toBe(op.t === "add" && before.rows.length < max ? 1 : 0);
116 expect(lost).toEqual(op.t === "remove" && ids(before).includes(touched!) ? [touched] : []);
117
118 // The attachment invariant: a surviving row the op did not target keeps
119 // its exact text and its exact File object, whatever moved around it.
120 for (const row of set.rows) {
121 const was = before.rows.find((r) => r.id === row.id);
122 if (!was || row.id === touched) continue;
123 expect(row.text).toBe(was.text);
124 expect(row.image).toBe(was.image);
125 }
126
127 // `correct` only ever names a live row (or nothing) — never an index,
128 // never a removed row.
129 if (set.correct !== null) expect(ids(set)).toContain(set.correct);
130 }
131
132 const out = submitChoices(set);
133 const outIds = out.choices.map((c) => c.id);
134
135 // Output is a subset of the live rows, in row order, no id invented or
136 // duplicated, and it is exactly the non-blank rows.
137 expect(new Set(outIds).size).toBe(outIds.length);
138 expect(outIds).toEqual(ids(set).filter((id) => set.rows.find((r) => r.id === id)!.text.trim()));
139 for (const [i, choice] of out.choices.entries()) {
140 const row = set.rows.find((r) => r.id === choice.id)!;
141 expect(choice.text).toBe(row.text.trim());
142 // The picture rides the id, not the position, after blanks are dropped.
143 expect(out.images[i]).toBe(row.image);
144 }
145
146 // The answer key survives the drop iff its row survived it.
147 const marked = set.rows.find((r) => r.id === set.correct);
148 expect(out.correct).toBe(marked && marked.text.trim() ? set.correct : null);
149 if (out.correct !== null) expect(outIds).toContain(out.correct);
150 }),
151 { numRuns: 500 },
152 );
153});
154
155test("reordering is invisible on the wire: same rows, same pictures, same answer key", () => {
156 fc.assert(
157 fc.property(startArb, fc.array(fc.record({ p: pick, q: pick }), { maxLength: 15 }), ({ set: start }, moves) => {
158 // Give every row a distinguishable picture so a positional mix-up shows.
159 let set = start.rows.reduce((acc, row) => setChoiceImage(acc, row.id, stampFile()), start);
160 const before = submitChoices(set);
161 for (const move of moves) {
162 set = moveChoice(set, at(set, move.p), Math.floor(move.q * Math.max(set.rows.length, 1)));
163 }
164 const after = submitChoices(set);
165
166 expect(after.correct).toBe(before.correct);
167 expect([...after.choices].sort((a, b) => a.id.localeCompare(b.id))).toEqual(
168 [...before.choices].sort((a, b) => a.id.localeCompare(b.id)),
169 );
170 // Each id keeps its own File across the reordering.
171 const pairs = (out: typeof before) => out.choices.map((c, i) => [c.id, out.images[i]] as const);
172 expect(new Map(pairs(after))).toEqual(new Map(pairs(before)));
173 }),
174 { numRuns: 300 },
175 );
176});