Skip to content

Commit

Permalink
update memory leak test for node v12.4
Browse files Browse the repository at this point in the history
Looking at heapUsed is not very reliable, because v8 in Node v12.4 just
uses more memory in general.  It's better to look at detached contexts,
which also does not require calling gc() to test.
  • Loading branch information
isaacs committed Jun 26, 2019
1 parent 4c1b072 commit c7b3374
Showing 1 changed file with 35 additions and 19 deletions.
54 changes: 35 additions & 19 deletions test/avoid-memory-leak.js
Original file line number Diff line number Diff line change
@@ -1,25 +1,41 @@
var importFresh = require('import-fresh');
var t = require('tap')
var v8
try {
v8 = require('v8')
} catch (er) {}

var previousHeapStats

function checkHeap (t) {
var v8stats = v8 ? v8.getHeapStatistics() : {}
var stats = process.memoryUsage()
if (typeof v8stats.number_of_detached_contexts === 'number')
t.equal(v8stats.number_of_detached_contexts, 0, 'no detached contexts')
else {
const memoryUsage = stats.heapUsed - previousHeapStats.heapUsed
const memoryUsageMB = Math.round(memoryUsage / Math.pow(1024, 2))
t.ok(memoryUsageMB < 2, 'expect less than 2MB difference, '
+ memoryUsageMB + 'MB difference found.');
}
}

t.test('no memory leak when loading multiple times', function(t) {
t.plan(1);
importFresh(process.cwd() + '/graceful-fs.js') // node 0.10-5 were getting: Cannot find module '../'
const mbUsedBefore = process.memoryUsage().heapUsed / Math.pow(1024, 2);
// simulate project with 4000 tests
var i = 0;
function importFreshGracefulFs() {
importFresh(process.cwd() + '/graceful-fs.js');
if (i < 4000) {
i++;
process.nextTick(() => importFreshGracefulFs());
} else {
global.gc();
const mbUsedAfter = process.memoryUsage().heapUsed / Math.pow(1024, 2);
// We expect less than a 2 MB difference
const memoryUsageMB = Math.round(mbUsedAfter - mbUsedBefore);
t.ok(memoryUsageMB < 2, 'We expect less than 2MB difference, but ' + memoryUsageMB + 'MB is still claimed.');
t.end();
}
t.plan(1);
importFresh(process.cwd() + '/graceful-fs.js') // node 0.10-5 were getting: Cannot find module '../'
previousHeapStats = process.memoryUsage()
// simulate project with 4000 tests
var i = 0;
function importFreshGracefulFs() {
importFresh(process.cwd() + '/graceful-fs.js');
if (i < 4000) {
i++;
process.nextTick(() => importFreshGracefulFs());
} else {
global.gc()
checkHeap(t);
t.end();
}
importFreshGracefulFs();
}
importFreshGracefulFs();
})

0 comments on commit c7b3374

Please sign in to comment.