From 05fd16048c622bad0e760151f5d0043970df179b Mon Sep 17 00:00:00 2001 From: Rich Trott Date: Sat, 14 Mar 2020 16:16:50 -0700 Subject: [PATCH] test: use Promise.all() in test-hash-seed MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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: https://github.com/nodejs/node/pull/32273 Reviewed-By: Michaël Zasso Reviewed-By: Tobias Nießen Reviewed-By: James M Snell Reviewed-By: Anto Aravinth --- test/pummel/test-hash-seed.js | 37 +++++++++++++++-------------------- 1 file changed, 16 insertions(+), 21 deletions(-) diff --git a/test/pummel/test-hash-seed.js b/test/pummel/test-hash-seed.js index 2b7f13593a9aa4..30edca32f6f852 100644 --- a/test/pummel/test-hash-seed.js +++ b/test/pummel/test-hash-seed.js @@ -1,31 +1,26 @@ 'use strict'; // Check that spawn child doesn't create duplicated entries -require('../common'); -const Countdown = require('../common/countdown'); -const REPETITIONS = 2; +const common = require('../common'); +const kRepetitions = 2; const assert = require('assert'); const fixtures = require('../common/fixtures'); -const { spawn } = require('child_process'); +const { promisify, debuglog } = require('util'); +const debug = debuglog('test'); + +const { execFile } = require('child_process'); +const execFilePromise = promisify(execFile); const targetScript = fixtures.path('guess-hash-seed.js'); -const seeds = []; -const requiredCallback = () => { - console.log(`Seeds: ${seeds}`); +const requiredCallback = common.mustCall((results) => { + const seeds = results.map((val) => val.stdout.trim()); + debug(`Seeds: ${seeds}`); assert.strictEqual(new Set(seeds).size, seeds.length); - assert.strictEqual(seeds.length, REPETITIONS); -}; - -const countdown = new Countdown(REPETITIONS, requiredCallback); + assert.strictEqual(seeds.length, kRepetitions); +}); -for (let i = 0; i < REPETITIONS; ++i) { - let result = ''; - const subprocess = spawn(process.execPath, [targetScript]); - subprocess.stdout.setEncoding('utf8'); - subprocess.stdout.on('data', (data) => { result += data; }); +const generateSeed = () => execFilePromise(process.execPath, [targetScript]); +const subprocesses = [...new Array(kRepetitions)].map(generateSeed); - subprocess.on('exit', () => { - seeds.push(result.trim()); - countdown.dec(); - }); -} +Promise.all(subprocesses) + .then(requiredCallback);