Skip to content

Commit

Permalink
fix(core): make randomString deterministic and allow larger values (#…
Browse files Browse the repository at this point in the history
  • Loading branch information
bernardobridge authored Jan 18, 2024
1 parent 1c936ad commit d7109dd
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 2 deletions.
13 changes: 11 additions & 2 deletions packages/core/lib/runner.js
Original file line number Diff line number Diff line change
Expand Up @@ -471,8 +471,17 @@ function $randomNumber(min, max) {
return _.random(min, max);
}

function $randomString(length) {
return Math.random().toString(36).substr(2, length);
function $randomString(length = 10) {
let s = '';
const alphabet =
'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
const alphabetLength = alphabet.length;

while (s.length < length) {
s += alphabet.charAt((Math.random() * alphabetLength) | 0);
}

return s;
}

function handleScriptHook(hook, script, hookEvents, contextVars = {}) {
Expand Down
30 changes: 30 additions & 0 deletions packages/core/test/core/unit/context_functions.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
const { test } = require('tap');
const { contextFuncs } = require('../../../lib/runner');

test('$randomString should return a string of the specified length', async function (t) {
const testStringOfLength = (length) => {
const defaultStringLength = 10;
const errors = [];
for (let i = 0; i < 10000; i++) {
const string = contextFuncs.$randomString(length);
if (string.length != (length || defaultStringLength)) {
errors.push(string);
}
}

t.ok(
errors.length == 0,
`All strings should be of length ${length || defaultStringLength}. Got ${
errors.length
} bad strings: ${JSON.stringify(errors)}`
);
};

//test with different size strings
testStringOfLength();
testStringOfLength(1);
testStringOfLength(2);
testStringOfLength(10);
testStringOfLength(100);
testStringOfLength(1000);
});

0 comments on commit d7109dd

Please sign in to comment.