Skip to content

Commit d7109dd

Browse files
fix(core): make randomString deterministic and allow larger values (#2342)
1 parent 1c936ad commit d7109dd

File tree

2 files changed

+41
-2
lines changed

2 files changed

+41
-2
lines changed

packages/core/lib/runner.js

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -471,8 +471,17 @@ function $randomNumber(min, max) {
471471
return _.random(min, max);
472472
}
473473

474-
function $randomString(length) {
475-
return Math.random().toString(36).substr(2, length);
474+
function $randomString(length = 10) {
475+
let s = '';
476+
const alphabet =
477+
'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
478+
const alphabetLength = alphabet.length;
479+
480+
while (s.length < length) {
481+
s += alphabet.charAt((Math.random() * alphabetLength) | 0);
482+
}
483+
484+
return s;
476485
}
477486

478487
function handleScriptHook(hook, script, hookEvents, contextVars = {}) {
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
const { test } = require('tap');
2+
const { contextFuncs } = require('../../../lib/runner');
3+
4+
test('$randomString should return a string of the specified length', async function (t) {
5+
const testStringOfLength = (length) => {
6+
const defaultStringLength = 10;
7+
const errors = [];
8+
for (let i = 0; i < 10000; i++) {
9+
const string = contextFuncs.$randomString(length);
10+
if (string.length != (length || defaultStringLength)) {
11+
errors.push(string);
12+
}
13+
}
14+
15+
t.ok(
16+
errors.length == 0,
17+
`All strings should be of length ${length || defaultStringLength}. Got ${
18+
errors.length
19+
} bad strings: ${JSON.stringify(errors)}`
20+
);
21+
};
22+
23+
//test with different size strings
24+
testStringOfLength();
25+
testStringOfLength(1);
26+
testStringOfLength(2);
27+
testStringOfLength(10);
28+
testStringOfLength(100);
29+
testStringOfLength(1000);
30+
});

0 commit comments

Comments
 (0)