1// Copyright 2020 the V8 project authors. All rights reserved. 2// Use of this source code is governed by a BSD-style license that can be 3// found in the LICENSE file. 4 5/** 6 * @fileoverview Test helpers. 7 */ 8 9'use strict'; 10 11const assert = require('assert'); 12const path = require('path'); 13const fs = require('fs'); 14 15const sourceHelpers = require('../source_helpers.js'); 16 17const BASE_DIR = path.join(path.dirname(__dirname), 'test_data'); 18const DB_DIR = path.join(BASE_DIR, 'fake_db'); 19 20const HEADER = `// Copyright 2020 the V8 project authors. All rights reserved. 21// Use of this source code is governed by a BSD-style license that can be 22// found in the LICENSE file. 23 24`; 25 26/** 27 * Create a function that returns one of `probs` when called. It rotates 28 * through the values. Useful to replace `random.random()` in tests using 29 * the probabilities that trigger different interesting cases. 30 */ 31function cycleProbabilitiesFun(probs) { 32 let index = 0; 33 return () => { 34 index = index % probs.length; 35 return probs[index++]; 36 }; 37} 38 39/** 40 * Replace Math.random with a deterministic pseudo-random function. 41 */ 42function deterministicRandom(sandbox) { 43 let seed = 1; 44 function random() { 45 const x = Math.sin(seed++) * 10000; 46 return x - Math.floor(x); 47 } 48 sandbox.stub(Math, 'random').callsFake(() => { return random(); }); 49} 50 51function loadTestData(relPath) { 52 return sourceHelpers.loadSource(BASE_DIR, relPath); 53} 54 55function assertExpectedResult(expectedPath, result) { 56 const absPath = path.join(BASE_DIR, expectedPath); 57 if (process.env.GENERATE) { 58 fs.writeFileSync(absPath, HEADER + result.trim() + '\n'); 59 return; 60 } 61 62 // Omit copyright header when comparing files. 63 const expected = fs.readFileSync(absPath, 'utf-8').trim().split('\n'); 64 expected.splice(0, 4); 65 assert.strictEqual(expected.join('\n'), result.trim()); 66} 67 68module.exports = { 69 BASE_DIR: BASE_DIR, 70 DB_DIR: DB_DIR, 71 assertExpectedResult: assertExpectedResult, 72 cycleProbabilitiesFun: cycleProbabilitiesFun, 73 deterministicRandom: deterministicRandom, 74 loadTestData: loadTestData, 75} 76