Skip to content

Commit

Permalink
Merge pull request #134 from sindresorhus/fork-cleanup
Browse files Browse the repository at this point in the history
Kill forked processes after tests are done
  • Loading branch information
Vadim Demedes committed Nov 5, 2015
2 parents 5a53900 + c81fb62 commit 1d565e4
Show file tree
Hide file tree
Showing 3 changed files with 13 additions and 39 deletions.
17 changes: 3 additions & 14 deletions cli.js
Original file line number Diff line number Diff line change
Expand Up @@ -133,8 +133,7 @@ function sum(arr, key) {
return result;
}

function exit(testRun) {
var results = testRun.results;
function exit(results) {
// assemble stats from all tests
var stats = results.map(function (result) {
return result.stats;
Expand All @@ -159,10 +158,7 @@ function exit(testRun) {
// correctly flush the output when multiple test files
process.stdout.write('');

// wait for the child processes to exit
testRun.childProcesses.finally(function () {
process.exit(failed > 0 ? 1 : 0);
});
process.exit(failed > 0 ? 1 : 0);
}

function init(files) {
Expand All @@ -182,14 +178,7 @@ function init(files) {

var tests = files.map(run);

return Promise.all(tests).then(function (results) {
return {
results: results,
childProcesses: Promise.map(tests, function (test) {
return test.kill();
})
};
});
return Promise.all(tests);
});
}

Expand Down
24 changes: 6 additions & 18 deletions lib/fork.js
Original file line number Diff line number Diff line change
Expand Up @@ -18,36 +18,24 @@ module.exports = function (args) {

var ps = childProcess.fork(babel, args, options);

var killed = false;
var killedPromise = new Promise(function (resolve) {
ps.on('exit', function (code) {
killed = true;
resolve(code);
});
});

function kill() {
if (!killed) {
ps.kill();
}
return killedPromise;
}

var promise = new Promise(function (resolve, reject) {
ps.on('results', function (results) {
resolve(results);

// after all tests are finished and results received
// kill the forked process, so AVA can exit safely
ps.kill();
});

// reject only when forked process failed
ps.on('error', reject);

ps.on('exit', function (code) {
if (code > 0) {
reject();
}
});
});

promise.kill = kill;

// emit `test` and `stats` events
ps.on('message', function (event) {
event.data.file = file;
Expand Down
11 changes: 4 additions & 7 deletions test/fork.js
Original file line number Diff line number Diff line change
Expand Up @@ -40,16 +40,13 @@ test('rejects on error and streams output', function (t) {
});
});

test('result.kill forcibly kills process', function (t) {
test('exit after tests are finished', function (t) {
t.plan(1);

var start = Date.now();
var promise = fork(fixture('long-running.js'))

fork(fixture('long-running.js'))
.on('exit', function () {
t.ok(Date.now() - start < 10000);
});

promise
.then(function () {
promise.kill();
});
});

0 comments on commit 1d565e4

Please sign in to comment.