Skip to content

Commit 8dbd7cf

Browse files
Trotttargos
authored andcommittedApr 22, 2020
test: use Promise.all() in test-hash-seed
We have several tests where a number of asynchronous processes need to finish before some checks happen. These are done in a number of ways, including (as here) using our Countdown testing module. I think Promise.all() may be the idiomatic and ergonomic way to go for a lot of these tests. Using this one to get feedback on the idea. PR-URL: #32273 Reviewed-By: Michaël Zasso <targos@protonmail.com> Reviewed-By: Tobias Nießen <tniessen@tnie.de> Reviewed-By: James M Snell <jasnell@gmail.com> Reviewed-By: Anto Aravinth <anto.aravinth.cse@gmail.com>
1 parent 46c751e commit 8dbd7cf

File tree

1 file changed

+16
-21
lines changed

1 file changed

+16
-21
lines changed
 

‎test/pummel/test-hash-seed.js

+16-21
Original file line numberDiff line numberDiff line change
@@ -1,31 +1,26 @@
11
'use strict';
22

33
// Check that spawn child doesn't create duplicated entries
4-
require('../common');
5-
const Countdown = require('../common/countdown');
6-
const REPETITIONS = 2;
4+
const common = require('../common');
5+
const kRepetitions = 2;
76
const assert = require('assert');
87
const fixtures = require('../common/fixtures');
9-
const { spawn } = require('child_process');
8+
const { promisify, debuglog } = require('util');
9+
const debug = debuglog('test');
10+
11+
const { execFile } = require('child_process');
12+
const execFilePromise = promisify(execFile);
1013
const targetScript = fixtures.path('guess-hash-seed.js');
11-
const seeds = [];
1214

13-
const requiredCallback = () => {
14-
console.log(`Seeds: ${seeds}`);
15+
const requiredCallback = common.mustCall((results) => {
16+
const seeds = results.map((val) => val.stdout.trim());
17+
debug(`Seeds: ${seeds}`);
1518
assert.strictEqual(new Set(seeds).size, seeds.length);
16-
assert.strictEqual(seeds.length, REPETITIONS);
17-
};
18-
19-
const countdown = new Countdown(REPETITIONS, requiredCallback);
19+
assert.strictEqual(seeds.length, kRepetitions);
20+
});
2021

21-
for (let i = 0; i < REPETITIONS; ++i) {
22-
let result = '';
23-
const subprocess = spawn(process.execPath, [targetScript]);
24-
subprocess.stdout.setEncoding('utf8');
25-
subprocess.stdout.on('data', (data) => { result += data; });
22+
const generateSeed = () => execFilePromise(process.execPath, [targetScript]);
23+
const subprocesses = [...new Array(kRepetitions)].map(generateSeed);
2624

27-
subprocess.on('exit', () => {
28-
seeds.push(result.trim());
29-
countdown.dec();
30-
});
31-
}
25+
Promise.all(subprocesses)
26+
.then(requiredCallback);

0 commit comments

Comments
 (0)
Please sign in to comment.