test_ThompsonSample.js (1826B)
1 "use strict"; 2 3 const eps = 1e-10; 4 5 add_task(function test_sortKeysvalues() { 6 const { sortKeysValues } = ChromeUtils.importESModule( 7 "resource://newtab/lib/SmartShortcutsRanker/ThomSample.mjs" 8 ); 9 10 const scores = [1.0, 2.0, 3.0]; 11 const keys = ["a", "b", "c"]; 12 13 const result = sortKeysValues(scores, keys); 14 15 Assert.deepEqual(result[0], ["c", "b", "a"], "check sorted order"); 16 Assert.deepEqual(result[1], [3.0, 2.0, 1.0], "check sorted order"); 17 }); 18 19 function makeRandomStub(values) { 20 let i = 0; 21 return function () { 22 if (i >= values.length) { 23 throw new Error("Too many Math.random() calls!"); 24 } 25 return values[i++]; 26 }; 27 } 28 29 add_task(function test_sampleGamma() { 30 const { sampleGamma } = ChromeUtils.importESModule( 31 "resource://newtab/lib/SmartShortcutsRanker/ThomSample.mjs" 32 ); 33 34 const testCases = [ 35 { 36 a: 2.0, 37 x: 1.0, 38 uni: 0.5, 39 expected: 3.319683214263267, 40 }, 41 ]; 42 43 for (const { a, x, uni, expected } of testCases) { 44 const stubbedNormal = makeRandomStub([x]); 45 const stubbedUni = makeRandomStub([uni]); 46 const result = sampleGamma(a, stubbedNormal, stubbedUni); 47 Assert.less( 48 Math.abs(result - expected), 49 eps, 50 `Expected ~${expected}, got ${result}` 51 ); 52 } 53 }); 54 55 add_task(function test_sampleNormal() { 56 const { sampleNormal } = ChromeUtils.importESModule( 57 "resource://newtab/lib/SmartShortcutsRanker/ThomSample.mjs" 58 ); 59 60 const testCases = [ 61 { 62 u: 0.85, 63 vRaw: 0.453, 64 expected: -0.09486258823529409, 65 }, 66 ]; 67 68 for (const { u, vRaw, expected } of testCases) { 69 const stubbedRandom = makeRandomStub([u, vRaw]); 70 const result = sampleNormal(stubbedRandom); 71 Assert.less( 72 Math.abs(result - expected), 73 eps, 74 `Expected ~${expected}, got ${result}` 75 ); 76 } 77 });