Repository Public
1/**2 * =============================================================================3 * SP BOUCHER | SOFTWARE & RESEARCH4 * ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project : UQO Éval — Le Grand Défi Immobilier8 * File : tests/unit/distractors.test.ts9 * Module : tests10 * Repository : https://git.spboucher.ai/uqo-eval-jeux11 * Project Website : https://jeux.uqo-eval.app12 * Created : 2026-11-2513 * Last Modified : 2026-11-2514 *15 * Author : Simon-Pierre Boucher16 * Position : Professor of Finance17 * Institution : Université du Québec en Outaouais (UQO)18 * Organization : SP Boucher19 * Website : https://spboucher.ai20 * Git : https://git.spboucher.ai21 *22 * Preferred Contact: contact@spboucher.ai23 * Development : dev@spboucher.ai24 * Support : support@spboucher.ai25 * Security/Admin : admin@spboucher.ai26 *27 * Copyright (c) 202628 * Simon-Pierre Boucher29 * All rights reserved where applicable. This file is governed by the30 * applicable project license, copyright notices and relevant law.31 * Existing third-party rights and notices remain unaffected.32 *33 * License : None specified (no license file in this repository)34 *35 * Do not embed credentials, private keys, access tokens,36 * certificates or confidential personal information.37 *38 * =============================================================================39 * END OF SP BOUCHER SOURCE HEADER40 * =============================================================================41 */4243import { describe, expect, it } from "vitest";44import { DEFAULT_BANDS, DIFFICULTIES, createRng, generateChoices, gridStep, validateChoices, type Difficulty } from "../../packages/engine/src/index.ts";4546const PRICES = [61_000, 89_900, 149_000, 249_900, 325_000, 399_999, 449_000, 575_500, 689_000, 925_000, 1_295_000, 2_480_000, 7_900_000, 14_999_999];4748function* cases(perPrice = 40): Generator<{ price: number; difficulty: Difficulty; seed: string }> {49 for (const difficulty of DIFFICULTIES) {50 for (const price of PRICES) {51 for (let i = 0; i < perPrice; i++) yield { price, difficulty, seed: `unit:${difficulty}:${price}:${i}` };52 }53 }54}5556describe("Moteur de prix fictifs — grille de repli (sans marché) : règles absolues", () => {57 it("produit exactement quatre prix entiers, strictement positifs et distincts, triés du moins cher au plus cher", () => {58 let n = 0;59 for (const c of cases()) {60 const g = generateChoices(c.price, c.difficulty, createRng(c.seed));61 expect(g.prices).toHaveLength(4);62 expect(new Set(g.prices).size).toBe(4);63 for (const p of g.prices) {64 expect(Number.isInteger(p)).toBe(true);65 expect(p).toBeGreaterThan(0);66 }67 expect([...g.prices].sort((a, b) => a - b)).toEqual(g.prices);68 n += 1;69 }70 expect(n).toBe(DIFFICULTIES.length * PRICES.length * 40);71 });7273 it("contient exactement une fois le prix réel, inchangé, au rang annoncé", () => {74 for (const c of cases()) {75 const g = generateChoices(c.price, c.difficulty, createRng(c.seed));76 expect(g.prices.filter((p) => p === c.price)).toHaveLength(1);77 expect(g.prices[g.correctRank]).toBe(c.price);78 expect(g.correctRank).toBeGreaterThanOrEqual(0);79 expect(g.correctRank).toBeLessThanOrEqual(3);80 }81 });8283 it("donne aux quatre prix la même terminaison modulo le pas de la grille (propriété du seul mode « grid »)", () => {84 for (const c of cases()) {85 const g = generateChoices(c.price, c.difficulty, createRng(c.seed));86 expect(g.source).toBe("grid");87 expect([5_000, 10_000, 50_000, 100_000]).toContain(g.step);88 const endings = new Set(g.prices.map((p) => ((p % g.step) + g.step) % g.step));89 expect(endings.size).toBe(1);90 expect([...endings][0]).toBe(c.price % g.step);91 }92 });9394 it("garde chaque écart entre voisins dans la plage de la difficulté, à l'arrondi de grille près", () => {95 let forced = 0;96 let total = 0;97 for (const c of cases()) {98 const band = DEFAULT_BANDS[c.difficulty];99 const g = generateChoices(c.price, c.difficulty, createRng(c.seed));100 const half = g.step / 2;101 for (let i = 0; i < 3; i++) {102 const lo = g.prices[i]!;103 const hi = g.prices[i + 1]!;104 total += 1;105 // Écart minimal forcé d'un pas lorsque l'arrondi ramènerait deux prix au même montant.106 if (hi - lo === g.step) {107 forced += 1;108 continue;109 }110 if (i >= g.correctRank) {111 // construit vers le haut : hi = arrondi(lo × (1 + g)), g ∈ [minGap, maxGap)112 expect(hi).toBeGreaterThanOrEqual(lo * (1 + band.minGap) - half);113 expect(hi).toBeLessThanOrEqual(lo * (1 + band.maxGap) + half);114 } else {115 // construit vers le bas : lo = arrondi(hi / (1 + g))116 expect(lo).toBeGreaterThanOrEqual(hi / (1 + band.maxGap) - half);117 expect(lo).toBeLessThanOrEqual(hi / (1 + band.minGap) + half);118 }119 }120 }121 expect(total).toBe(DIFFICULTIES.length * PRICES.length * 40 * 3);122 // L'écart forcé ne concerne que les petits prix aux difficultés fines : il doit rester minoritaire.123 expect(forced / total).toBeLessThan(0.2);124 });125126 it("rapporte dans `gaps` les écarts relatifs effectifs entre prix voisins", () => {127 const g = generateChoices(449_000, "intermediaire", createRng("gaps"));128 expect(g.gaps).toHaveLength(3);129 for (let i = 0; i < 3; i++) expect(g.gaps[i]).toBeCloseTo(g.prices[i + 1]! / g.prices[i]! - 1, 12);130 });131132 it("est reproductible avec la même graine et varie avec une autre graine", () => {133 const a = generateChoices(449_000, "avance", createRng("graine-A"));134 const b = generateChoices(449_000, "avance", createRng("graine-A"));135 expect(b).toEqual(a);136 const others = Array.from({ length: 20 }, (_, i) => generateChoices(449_000, "avance", createRng(`graine-B${i}`)).prices.join("|"));137 expect(new Set(others).size).toBeGreaterThan(10);138 });139140 it("resserre les écarts quand la difficulté augmente (étendue relative médiane décroissante)", () => {141 const spread = (difficulty: Difficulty): number => {142 const values = Array.from({ length: 400 }, (_, i) => {143 const g = generateChoices(450_000, difficulty, createRng(`spread:${difficulty}:${i}`));144 return g.prices[3] / g.prices[0];145 }).sort((x, y) => x - y);146 return values[200]!;147 };148 const s = DIFFICULTIES.map(spread);149 expect(s[0]).toBeGreaterThan(s[1]!);150 expect(s[1]).toBeGreaterThan(s[2]!);151 expect(s[2]).toBeGreaterThan(s[3]!);152 });153154 it("refuse un prix réel nul, négatif ou non fini", () => {155 for (const bad of [0, -1, Number.NaN, Number.POSITIVE_INFINITY]) {156 expect(() => generateChoices(bad, "initiation", createRng("x"))).toThrow(/Prix réel invalide/);157 }158 });159160 it("respecte les bornes de marché quand elles laissent de la place, sans jamais modifier le prix réel", () => {161 for (let i = 0; i < 300; i++) {162 const g = generateChoices(300_000, "initiation", createRng(`bornes:${i}`), { floorPrice: 150_000, ceilPrice: 900_000 });163 expect(g.prices[0]).toBeGreaterThanOrEqual(150_000);164 expect(g.prices[3]).toBeLessThanOrEqual(900_000);165 expect(g.prices[g.correctRank]).toBe(300_000);166 }167 });168169 it("déplace le rang (rankAdjusted) lorsque le plancher du marché interdit des prix plus bas", () => {170 let adjusted = 0;171 for (let i = 0; i < 200; i++) {172 // Le prix réel est au plancher : aucun prix fictif ne peut être inférieur.173 const g = generateChoices(200_000, "initiation", createRng(`plancher:${i}`), { floorPrice: 200_000 });174 expect(g.correctRank).toBe(0);175 expect(g.prices[0]).toBe(200_000);176 if (g.rankAdjusted) adjusted += 1;177 }178 // Trois tirages sur quatre visaient un autre rang.179 expect(adjusted).toBeGreaterThan(120);180 expect(adjusted).toBeLessThan(180);181 });182183 it("signale rankAdjusted = false quand aucune borne ne contraint le tirage", () => {184 for (let i = 0; i < 300; i++) {185 expect(generateChoices(450_000, "expert", createRng(`libre:${i}`)).rankAdjusted).toBe(false);186 }187 });188189 it("reste valide pour un prix très bas (aucun prix nul ou négatif)", () => {190 for (const difficulty of DIFFICULTIES) {191 for (let i = 0; i < 200; i++) {192 const g = generateChoices(12_000, difficulty, createRng(`bas:${difficulty}:${i}`));193 expect(validateChoices(g.prices, 12_000)).toBeNull();194 expect(g.prices[0]).toBeGreaterThan(0);195 }196 }197 });198});199200describe("gridStep", () => {201 it("retient le plus grand pas inférieur ou égal à la moitié de l'écart minimal visé", () => {202 expect(gridStep(450_000, 0.15)).toBe(10_000); // 33 750 → 10 000203 expect(gridStep(1_400_000, 0.15)).toBe(100_000); // 105 000 → 100 000204 expect(gridStep(700_000, 0.15)).toBe(50_000); // 52 500 → 50 000205 expect(gridStep(450_000, 0.04)).toBe(5_000); // 9 000 → 5 000206 expect(gridStep(100_000, 0.02)).toBe(5_000); // 1 000 → pas minimal207 });208});209210describe("validateChoices", () => {211 it("accepte quatre prix distincts dont un seul est le prix réel", () => {212 expect(validateChoices([300_000, 350_000, 400_000, 450_000], 350_000)).toBeNull();213 });214 it("rejette un nombre de prix différent de quatre", () => {215 expect(validateChoices([1, 2, 3], 1)).toMatch(/quatre/);216 expect(validateChoices([1, 2, 3, 4, 5], 1)).toMatch(/quatre/);217 });218 it("rejette un prix non entier, nul ou négatif", () => {219 expect(validateChoices([300_000.5, 350_000, 400_000, 450_000], 350_000)).toMatch(/non entier/);220 expect(validateChoices([0, 350_000, 400_000, 450_000], 350_000)).toMatch(/nul/);221 expect(validateChoices([-5, 350_000, 400_000, 450_000], 350_000)).toMatch(/négatif/);222 });223 it("rejette les doublons", () => {224 expect(validateChoices([350_000, 350_000, 400_000, 450_000], 350_000)).toMatch(/double/);225 });226 it("rejette l'absence de la bonne réponse", () => {227 expect(validateChoices([300_000, 350_000, 400_000, 450_000], 375_000)).toMatch(/exactement une bonne réponse/);228 });229});230231describe("Moteur de prix fictifs — tirage sur le marché réel (marketPrices)", () => {232 // Marché synthétique de 6 000 annonces : prix log-uniformes aux terminaisons « de vendeur », triés, doublons conservés.233 const ENDINGS = [0, 9_000, 9_900, 5_000, 4_900, 9_999];234 const marketRng = createRng("marche-unitaire");235 const market = Array.from({ length: 6_000 }, () => {236 const base = Math.floor(Math.exp(marketRng.range(Math.log(120_000), Math.log(1_800_000))) / 10_000) * 10_000;237 return base + marketRng.pick(ENDINGS);238 }).sort((a, b) => a - b);239 const frozen = [...market];240 const inMarket = new Set(market);241 const sample = Array.from({ length: 150 }, (_, i) => market[500 + i * 33]!);242243 function* marketCases(): Generator<{ price: number; difficulty: Difficulty; seed: string }> {244 for (const difficulty of DIFFICULTIES) for (const [i, price] of sample.entries()) for (let k = 0; k < 4; k++) yield { price, difficulty, seed: `marche:${difficulty}:${i}:${k}` };245 }246247 it("produit quatre prix entiers distincts et triés, dont exactement un est le prix réel inchangé", () => {248 let n = 0;249 for (const c of marketCases()) {250 const g = generateChoices(c.price, c.difficulty, createRng(c.seed), { marketPrices: market });251 expect(validateChoices(g.prices, c.price)).toBeNull();252 expect([...g.prices].sort((a, b) => a - b)).toEqual(g.prices);253 expect(g.prices[g.correctRank]).toBe(c.price);254 n += 1;255 }256 expect(n).toBe(DIFFICULTIES.length * 150 * 4);257 });258259 it("tire chaque prix fictif parmi les prix réellement présents sur le marché quand la source est « market »", () => {260 let fromMarket = 0;261 let total = 0;262 for (const c of marketCases()) {263 const g = generateChoices(c.price, c.difficulty, createRng(c.seed), { marketPrices: market });264 total += 1;265 if (g.source !== "market") continue;266 fromMarket += 1;267 for (const p of g.prices) expect(inMarket.has(p), `${p}`).toBe(true);268 }269 // au cœur du marché, le repli sur la grille doit rester l'exception270 expect(fromMarket / total).toBeGreaterThan(0.95);271 });272273 it("ne partage plus une terminaison commune : les prix fictifs portent les terminaisons du marché", () => {274 let mixed = 0;275 let total = 0;276 for (const c of marketCases()) {277 const g = generateChoices(c.price, c.difficulty, createRng(c.seed), { marketPrices: market });278 if (g.source !== "market") continue;279 total += 1;280 for (const p of g.prices) expect(ENDINGS).toContain(p % 10_000);281 if (new Set(g.prices.map((p) => p % 10_000)).size > 1) mixed += 1;282 }283 expect(mixed / total).toBeGreaterThan(0.5);284 });285286 it("borne chaque écart réalisé à [0,5 × minGap ; 1,75 × maxGap] quand la source est « market »", () => {287 for (const c of marketCases()) {288 const band = DEFAULT_BANDS[c.difficulty];289 const g = generateChoices(c.price, c.difficulty, createRng(c.seed), { marketPrices: market });290 if (g.source !== "market") continue;291 for (const gap of g.gaps) {292 expect(gap).toBeGreaterThanOrEqual(band.minGap * 0.5 - 1e-12);293 expect(gap).toBeLessThanOrEqual(band.maxGap * 1.75 + 1e-12);294 }295 }296 });297298 it("est reproductible avec la même graine, varie avec une autre, et ne modifie pas le marché reçu", () => {299 const a = generateChoices(sample[40]!, "avance", createRng("m-A"), { marketPrices: market });300 expect(generateChoices(sample[40]!, "avance", createRng("m-A"), { marketPrices: market })).toEqual(a);301 const others = new Set(Array.from({ length: 20 }, (_, i) => generateChoices(sample[40]!, "avance", createRng(`m-B${i}`), { marketPrices: market }).prices.join("|")));302 expect(others.size).toBeGreaterThan(10);303 expect(market).toEqual(frozen);304 });305306 it("accepte un prix réel absent du marché (il reste l'un des quatre choix)", () => {307 for (let i = 0; i < 100; i++) {308 const price = 237_123 + i * 10_000;309 expect(inMarket.has(price)).toBe(false);310 const g = generateChoices(price, "intermediaire", createRng(`absent:${i}`), { marketPrices: market });311 expect(validateChoices(g.prices, price)).toBeNull();312 expect(g.source).toBe("market");313 }314 });315316 it("ignore un marché trop mince (moins de 200 prix) et retombe sur la grille", () => {317 const thin = market.filter((_, i) => i % 40 === 0);318 expect(thin.length).toBeLessThan(200);319 for (let i = 0; i < 50; i++) {320 const g = generateChoices(450_000, "avance", createRng(`mince:${i}`), { marketPrices: thin });321 expect(g.source).toBe("grid");322 expect(new Set(g.prices.map((p) => p % g.step)).size).toBe(1);323 }324 expect(generateChoices(450_000, "avance", createRng("vide"), { marketPrices: [] }).source).toBe("grid");325 });326327 it("retombe sur la grille pour un prix très au-delà du marché, sans jamais échouer", () => {328 for (const price of [9_500_000, 14_000_000, 20_000]) {329 for (const difficulty of DIFFICULTIES) {330 const g = generateChoices(price, difficulty, createRng(`hors:${price}:${difficulty}`), { marketPrices: market });331 expect(validateChoices(g.prices, price)).toBeNull();332 expect(g.source).toBe("grid");333 }334 }335 });336337 it("respecte les bornes de marché (plancher et plafond) avec la source « market »", () => {338 for (let i = 0; i < 200; i++) {339 const g = generateChoices(sample[i % 150]!, "initiation", createRng(`bornes-m:${i}`), { marketPrices: market, floorPrice: 100_000, ceilPrice: 2_500_000 });340 expect(g.prices[0]).toBeGreaterThanOrEqual(Math.min(100_000, g.prices[g.correctRank]!));341 expect(g.prices[3]).toBeLessThanOrEqual(2_500_000);342 }343 });344});345346