test: cleanup IIFE tests

A number of test files use IIFEs to separate distinct tests from
each other in the same file. The project has been moving toward
using block scopes and let/const in favor of IIFEs. This commit
moves IIFE tests to block scopes. Some additional cleanup such
as use of strictEqual() and common.mustCall() is also included.

PR-URL: https://github.com/nodejs/node/pull/7694
Reviewed-By: Santiago Gimeno <santiago.gimeno@gmail.com>
This commit is contained in:
cjihrig 2016-07-12 19:47:32 -04:00
parent 4220c24b17
commit 4a408321d9
34 changed files with 664 additions and 749 deletions

View File

@ -35,19 +35,16 @@ function getall() {
if (count >= todo) if (count >= todo)
return; return;
(function() { const req = net.connect(server.address().port, server.address().address);
var req = net.connect(server.address().port, server.address().address); req.resume();
req.resume(); req.setTimeout(10, function() {
req.setTimeout(10, function() { req.destroy();
//console.log('timeout (expected)') done++;
req.destroy(); global.gc();
done++; });
global.gc();
});
count++; count++;
weak(req, afterGC); weak(req, afterGC);
})();
setImmediate(getall); setImmediate(getall);
} }
@ -76,4 +73,3 @@ function status() {
}, 200); }, 200);
} }
} }

View File

@ -1038,28 +1038,28 @@ Buffer.from(Buffer.allocUnsafe(0), 0, 0);
// GH-5110 // GH-5110
(function() { {
const buffer = Buffer.from('test'); const buffer = Buffer.from('test');
const string = JSON.stringify(buffer); const string = JSON.stringify(buffer);
assert.equal(string, '{"type":"Buffer","data":[116,101,115,116]}'); assert.strictEqual(string, '{"type":"Buffer","data":[116,101,115,116]}');
assert.deepStrictEqual(buffer, JSON.parse(string, function(key, value) { assert.deepStrictEqual(buffer, JSON.parse(string, function(key, value) {
return value && value.type === 'Buffer' return value && value.type === 'Buffer'
? Buffer.from(value.data) ? Buffer.from(value.data)
: value; : value;
})); }));
})(); }
// issue GH-7849 // issue GH-7849
(function() { {
var buf = Buffer.from('test'); const buf = Buffer.from('test');
var json = JSON.stringify(buf); const json = JSON.stringify(buf);
var obj = JSON.parse(json); const obj = JSON.parse(json);
var copy = Buffer.from(obj); const copy = Buffer.from(obj);
assert(buf.equals(copy)); assert(buf.equals(copy));
})(); }
// issue GH-4331 // issue GH-4331
assert.throws(function() { assert.throws(function() {
@ -1165,30 +1165,30 @@ assert.throws(function() {
}); });
// test for common read(U)IntLE/BE // test for common read(U)IntLE/BE
(function() { {
var buf = Buffer.from([0x01, 0x02, 0x03, 0x04, 0x05, 0x06]); var buf = Buffer.from([0x01, 0x02, 0x03, 0x04, 0x05, 0x06]);
assert.equal(buf.readUIntLE(0, 1), 0x01); assert.strictEqual(buf.readUIntLE(0, 1), 0x01);
assert.equal(buf.readUIntBE(0, 1), 0x01); assert.strictEqual(buf.readUIntBE(0, 1), 0x01);
assert.equal(buf.readUIntLE(0, 3), 0x030201); assert.strictEqual(buf.readUIntLE(0, 3), 0x030201);
assert.equal(buf.readUIntBE(0, 3), 0x010203); assert.strictEqual(buf.readUIntBE(0, 3), 0x010203);
assert.equal(buf.readUIntLE(0, 5), 0x0504030201); assert.strictEqual(buf.readUIntLE(0, 5), 0x0504030201);
assert.equal(buf.readUIntBE(0, 5), 0x0102030405); assert.strictEqual(buf.readUIntBE(0, 5), 0x0102030405);
assert.equal(buf.readUIntLE(0, 6), 0x060504030201); assert.strictEqual(buf.readUIntLE(0, 6), 0x060504030201);
assert.equal(buf.readUIntBE(0, 6), 0x010203040506); assert.strictEqual(buf.readUIntBE(0, 6), 0x010203040506);
assert.equal(buf.readIntLE(0, 1), 0x01); assert.strictEqual(buf.readIntLE(0, 1), 0x01);
assert.equal(buf.readIntBE(0, 1), 0x01); assert.strictEqual(buf.readIntBE(0, 1), 0x01);
assert.equal(buf.readIntLE(0, 3), 0x030201); assert.strictEqual(buf.readIntLE(0, 3), 0x030201);
assert.equal(buf.readIntBE(0, 3), 0x010203); assert.strictEqual(buf.readIntBE(0, 3), 0x010203);
assert.equal(buf.readIntLE(0, 5), 0x0504030201); assert.strictEqual(buf.readIntLE(0, 5), 0x0504030201);
assert.equal(buf.readIntBE(0, 5), 0x0102030405); assert.strictEqual(buf.readIntBE(0, 5), 0x0102030405);
assert.equal(buf.readIntLE(0, 6), 0x060504030201); assert.strictEqual(buf.readIntLE(0, 6), 0x060504030201);
assert.equal(buf.readIntBE(0, 6), 0x010203040506); assert.strictEqual(buf.readIntBE(0, 6), 0x010203040506);
})(); }
// test for common write(U)IntLE/BE // test for common write(U)IntLE/BE
(function() { {
var buf = Buffer.allocUnsafe(3); let buf = Buffer.allocUnsafe(3);
buf.writeUIntLE(0x123456, 0, 3); buf.writeUIntLE(0x123456, 0, 3);
assert.deepStrictEqual(buf.toJSON().data, [0x56, 0x34, 0x12]); assert.deepStrictEqual(buf.toJSON().data, [0x56, 0x34, 0x12]);
assert.equal(buf.readUIntLE(0, 3), 0x123456); assert.equal(buf.readUIntLE(0, 3), 0x123456);
@ -1277,11 +1277,11 @@ assert.throws(function() {
buf.writeIntBE(-0x0012000000, 0, 5); buf.writeIntBE(-0x0012000000, 0, 5);
assert.deepStrictEqual(buf.toJSON().data, [0xff, 0xee, 0x00, 0x00, 0x00]); assert.deepStrictEqual(buf.toJSON().data, [0xff, 0xee, 0x00, 0x00, 0x00]);
assert.equal(buf.readIntBE(0, 5), -0x0012000000); assert.equal(buf.readIntBE(0, 5), -0x0012000000);
})(); }
// test Buffer slice // test Buffer slice
(function() { {
var buf = Buffer.from('0123456789'); const buf = Buffer.from('0123456789');
assert.equal(buf.slice(-10, 10), '0123456789'); assert.equal(buf.slice(-10, 10), '0123456789');
assert.equal(buf.slice(-20, 10), '0123456789'); assert.equal(buf.slice(-20, 10), '0123456789');
assert.equal(buf.slice(-20, -10), ''); assert.equal(buf.slice(-20, -10), '');
@ -1314,7 +1314,7 @@ assert.throws(function() {
assert.equal(buf.slice(0, -i), s.slice(0, -i)); assert.equal(buf.slice(0, -i), s.slice(0, -i));
} }
var utf16Buf = Buffer.from('0123456789', 'utf16le'); const utf16Buf = Buffer.from('0123456789', 'utf16le');
assert.deepStrictEqual(utf16Buf.slice(0, 6), Buffer.from('012', 'utf16le')); assert.deepStrictEqual(utf16Buf.slice(0, 6), Buffer.from('012', 'utf16le'));
assert.equal(buf.slice('0', '1'), '0'); assert.equal(buf.slice('0', '1'), '0');
@ -1328,7 +1328,7 @@ assert.throws(function() {
// try to slice a zero length Buffer // try to slice a zero length Buffer
// see https://github.com/joyent/node/issues/5881 // see https://github.com/joyent/node/issues/5881
Buffer.alloc(0).slice(0, 1); Buffer.alloc(0).slice(0, 1);
})(); }
// Regression test for #5482: should throw but not assert in C++ land. // Regression test for #5482: should throw but not assert in C++ land.
assert.throws(function() { assert.throws(function() {
@ -1337,20 +1337,20 @@ assert.throws(function() {
// Regression test for #6111. Constructing a buffer from another buffer // Regression test for #6111. Constructing a buffer from another buffer
// should a) work, and b) not corrupt the source buffer. // should a) work, and b) not corrupt the source buffer.
(function() { {
var a = [0]; let a = [0];
for (let i = 0; i < 7; ++i) a = a.concat(a); for (let i = 0; i < 7; ++i) a = a.concat(a);
a = a.map(function(_, i) { return i; }); a = a.map(function(_, i) { return i; });
const b = Buffer.from(a); const b = Buffer.from(a);
const c = Buffer.from(b); const c = Buffer.from(b);
assert.equal(b.length, a.length); assert.strictEqual(b.length, a.length);
assert.equal(c.length, a.length); assert.strictEqual(c.length, a.length);
for (let i = 0, k = a.length; i < k; ++i) { for (let i = 0, k = a.length; i < k; ++i) {
assert.equal(a[i], i); assert.strictEqual(a[i], i);
assert.equal(b[i], i); assert.strictEqual(b[i], i);
assert.equal(c[i], i); assert.strictEqual(c[i], i);
} }
})(); }
assert.throws(function() { assert.throws(function() {

View File

@ -1054,28 +1054,28 @@ Buffer(Buffer(0), 0, 0);
// GH-5110 // GH-5110
(function() { {
const buffer = new Buffer('test'); const buffer = new Buffer('test');
const string = JSON.stringify(buffer); const string = JSON.stringify(buffer);
assert.equal(string, '{"type":"Buffer","data":[116,101,115,116]}'); assert.strictEqual(string, '{"type":"Buffer","data":[116,101,115,116]}');
assert.deepStrictEqual(buffer, JSON.parse(string, function(key, value) { assert.deepStrictEqual(buffer, JSON.parse(string, function(key, value) {
return value && value.type === 'Buffer' return value && value.type === 'Buffer'
? new Buffer(value.data) ? new Buffer(value.data)
: value; : value;
})); }));
})(); }
// issue GH-7849 // issue GH-7849
(function() { {
var buf = new Buffer('test'); const buf = new Buffer('test');
var json = JSON.stringify(buf); const json = JSON.stringify(buf);
var obj = JSON.parse(json); const obj = JSON.parse(json);
var copy = new Buffer(obj); const copy = new Buffer(obj);
assert(buf.equals(copy)); assert(buf.equals(copy));
})(); }
// issue GH-4331 // issue GH-4331
assert.throws(function() { assert.throws(function() {
@ -1191,30 +1191,30 @@ assert.throws(function() {
}); });
// test for common read(U)IntLE/BE // test for common read(U)IntLE/BE
(function() { {
var buf = new Buffer([0x01, 0x02, 0x03, 0x04, 0x05, 0x06]); const buf = new Buffer([0x01, 0x02, 0x03, 0x04, 0x05, 0x06]);
assert.equal(buf.readUIntLE(0, 1), 0x01); assert.strictEqual(buf.readUIntLE(0, 1), 0x01);
assert.equal(buf.readUIntBE(0, 1), 0x01); assert.strictEqual(buf.readUIntBE(0, 1), 0x01);
assert.equal(buf.readUIntLE(0, 3), 0x030201); assert.strictEqual(buf.readUIntLE(0, 3), 0x030201);
assert.equal(buf.readUIntBE(0, 3), 0x010203); assert.strictEqual(buf.readUIntBE(0, 3), 0x010203);
assert.equal(buf.readUIntLE(0, 5), 0x0504030201); assert.strictEqual(buf.readUIntLE(0, 5), 0x0504030201);
assert.equal(buf.readUIntBE(0, 5), 0x0102030405); assert.strictEqual(buf.readUIntBE(0, 5), 0x0102030405);
assert.equal(buf.readUIntLE(0, 6), 0x060504030201); assert.strictEqual(buf.readUIntLE(0, 6), 0x060504030201);
assert.equal(buf.readUIntBE(0, 6), 0x010203040506); assert.strictEqual(buf.readUIntBE(0, 6), 0x010203040506);
assert.equal(buf.readIntLE(0, 1), 0x01); assert.strictEqual(buf.readIntLE(0, 1), 0x01);
assert.equal(buf.readIntBE(0, 1), 0x01); assert.strictEqual(buf.readIntBE(0, 1), 0x01);
assert.equal(buf.readIntLE(0, 3), 0x030201); assert.strictEqual(buf.readIntLE(0, 3), 0x030201);
assert.equal(buf.readIntBE(0, 3), 0x010203); assert.strictEqual(buf.readIntBE(0, 3), 0x010203);
assert.equal(buf.readIntLE(0, 5), 0x0504030201); assert.strictEqual(buf.readIntLE(0, 5), 0x0504030201);
assert.equal(buf.readIntBE(0, 5), 0x0102030405); assert.strictEqual(buf.readIntBE(0, 5), 0x0102030405);
assert.equal(buf.readIntLE(0, 6), 0x060504030201); assert.strictEqual(buf.readIntLE(0, 6), 0x060504030201);
assert.equal(buf.readIntBE(0, 6), 0x010203040506); assert.strictEqual(buf.readIntBE(0, 6), 0x010203040506);
})(); }
// test for common write(U)IntLE/BE // test for common write(U)IntLE/BE
(function() { {
var buf = Buffer(3); let buf = Buffer(3);
buf.writeUIntLE(0x123456, 0, 3); buf.writeUIntLE(0x123456, 0, 3);
assert.deepStrictEqual(buf.toJSON().data, [0x56, 0x34, 0x12]); assert.deepStrictEqual(buf.toJSON().data, [0x56, 0x34, 0x12]);
assert.equal(buf.readUIntLE(0, 3), 0x123456); assert.equal(buf.readUIntLE(0, 3), 0x123456);
@ -1303,11 +1303,11 @@ assert.throws(function() {
buf.writeIntBE(-0x0012000000, 0, 5); buf.writeIntBE(-0x0012000000, 0, 5);
assert.deepStrictEqual(buf.toJSON().data, [0xff, 0xee, 0x00, 0x00, 0x00]); assert.deepStrictEqual(buf.toJSON().data, [0xff, 0xee, 0x00, 0x00, 0x00]);
assert.equal(buf.readIntBE(0, 5), -0x0012000000); assert.equal(buf.readIntBE(0, 5), -0x0012000000);
})(); }
// test Buffer slice // test Buffer slice
(function() { {
var buf = new Buffer('0123456789'); const buf = new Buffer('0123456789');
assert.equal(buf.slice(-10, 10), '0123456789'); assert.equal(buf.slice(-10, 10), '0123456789');
assert.equal(buf.slice(-20, 10), '0123456789'); assert.equal(buf.slice(-20, 10), '0123456789');
assert.equal(buf.slice(-20, -10), ''); assert.equal(buf.slice(-20, -10), '');
@ -1340,7 +1340,7 @@ assert.throws(function() {
assert.equal(buf.slice(0, -i), s.slice(0, -i)); assert.equal(buf.slice(0, -i), s.slice(0, -i));
} }
var utf16Buf = new Buffer('0123456789', 'utf16le'); const utf16Buf = new Buffer('0123456789', 'utf16le');
assert.deepStrictEqual(utf16Buf.slice(0, 6), Buffer('012', 'utf16le')); assert.deepStrictEqual(utf16Buf.slice(0, 6), Buffer('012', 'utf16le'));
assert.equal(buf.slice('0', '1'), '0'); assert.equal(buf.slice('0', '1'), '0');
@ -1354,7 +1354,7 @@ assert.throws(function() {
// try to slice a zero length Buffer // try to slice a zero length Buffer
// see https://github.com/joyent/node/issues/5881 // see https://github.com/joyent/node/issues/5881
SlowBuffer(0).slice(0, 1); SlowBuffer(0).slice(0, 1);
})(); }
// Regression test for #5482: should throw but not assert in C++ land. // Regression test for #5482: should throw but not assert in C++ land.
assert.throws(function() { assert.throws(function() {
@ -1363,20 +1363,20 @@ assert.throws(function() {
// Regression test for #6111. Constructing a buffer from another buffer // Regression test for #6111. Constructing a buffer from another buffer
// should a) work, and b) not corrupt the source buffer. // should a) work, and b) not corrupt the source buffer.
(function() { {
var a = [0]; let a = [0];
for (let i = 0; i < 7; ++i) a = a.concat(a); for (let i = 0; i < 7; ++i) a = a.concat(a);
a = a.map(function(_, i) { return i; }); a = a.map(function(_, i) { return i; });
const b = Buffer(a); const b = Buffer(a);
const c = Buffer(b); const c = Buffer(b);
assert.equal(b.length, a.length); assert.strictEqual(b.length, a.length);
assert.equal(c.length, a.length); assert.strictEqual(c.length, a.length);
for (let i = 0, k = a.length; i < k; ++i) { for (let i = 0, k = a.length; i < k; ++i) {
assert.equal(a[i], i); assert.strictEqual(a[i], i);
assert.equal(b[i], i); assert.strictEqual(b[i], i);
assert.equal(c[i], i); assert.strictEqual(c[i], i);
} }
})(); }
assert.throws(function() { assert.throws(function() {

View File

@ -44,18 +44,11 @@ if (common.isWindows) {
} }
// Assume does-not-exist doesn't exist, expect exitCode=-1 and errno=ENOENT // Assume does-not-exist doesn't exist, expect exitCode=-1 and errno=ENOENT
(function() { {
var errors = 0; testCwd({cwd: 'does-not-exist'}, -1).on('error', common.mustCall(function(e) {
testCwd({cwd: 'does-not-exist'}, -1).on('error', function(e) {
assert.equal(e.code, 'ENOENT'); assert.equal(e.code, 'ENOENT');
errors++; }));
}); }
process.on('exit', function() {
assert.equal(errors, 1);
});
})();
// Spawn() shouldn't try to chdir() so this should just work // Spawn() shouldn't try to chdir() so this should just work
testCwd(undefined, 0); testCwd(undefined, 0);

View File

@ -322,34 +322,34 @@ for (var i in TEST_CASES) {
continue; continue;
} }
(function() { {
var encrypt = crypto.createCipheriv(test.algo, const encrypt = crypto.createCipheriv(test.algo,
Buffer.from(test.key, 'hex'), Buffer.from(test.iv, 'hex')); Buffer.from(test.key, 'hex'), Buffer.from(test.iv, 'hex'));
if (test.aad) if (test.aad)
encrypt.setAAD(Buffer.from(test.aad, 'hex')); encrypt.setAAD(Buffer.from(test.aad, 'hex'));
var inputEncoding = test.plainIsHex ? 'hex' : 'ascii'; const inputEncoding = test.plainIsHex ? 'hex' : 'ascii';
var hex = encrypt.update(test.plain, inputEncoding, 'hex'); let hex = encrypt.update(test.plain, inputEncoding, 'hex');
hex += encrypt.final('hex'); hex += encrypt.final('hex');
var auth_tag = encrypt.getAuthTag(); const auth_tag = encrypt.getAuthTag();
// only test basic encryption run if output is marked as tampered. // only test basic encryption run if output is marked as tampered.
if (!test.tampered) { if (!test.tampered) {
assert.equal(hex, test.ct); assert.strictEqual(hex, test.ct);
assert.equal(auth_tag.toString('hex'), test.tag); assert.strictEqual(auth_tag.toString('hex'), test.tag);
} }
})(); }
(function() { {
var decrypt = crypto.createDecipheriv(test.algo, const decrypt = crypto.createDecipheriv(test.algo,
Buffer.from(test.key, 'hex'), Buffer.from(test.iv, 'hex')); Buffer.from(test.key, 'hex'), Buffer.from(test.iv, 'hex'));
decrypt.setAuthTag(Buffer.from(test.tag, 'hex')); decrypt.setAuthTag(Buffer.from(test.tag, 'hex'));
if (test.aad) if (test.aad)
decrypt.setAAD(Buffer.from(test.aad, 'hex')); decrypt.setAAD(Buffer.from(test.aad, 'hex'));
var outputEncoding = test.plainIsHex ? 'hex' : 'ascii'; const outputEncoding = test.plainIsHex ? 'hex' : 'ascii';
var msg = decrypt.update(test.ct, 'hex', outputEncoding); let msg = decrypt.update(test.ct, 'hex', outputEncoding);
if (!test.tampered) { if (!test.tampered) {
msg += decrypt.final(outputEncoding); msg += decrypt.final(outputEncoding);
assert.equal(msg, test.plain); assert.equal(msg, test.plain);
@ -357,48 +357,48 @@ for (var i in TEST_CASES) {
// assert that final throws if input data could not be verified! // assert that final throws if input data could not be verified!
assert.throws(function() { decrypt.final('ascii'); }, / auth/); assert.throws(function() { decrypt.final('ascii'); }, / auth/);
} }
})(); }
(function() { {
if (!test.password) return; if (!test.password) return;
if (common.hasFipsCrypto) { if (common.hasFipsCrypto) {
assert.throws(() => { crypto.createCipher(test.algo, test.password); }, assert.throws(() => { crypto.createCipher(test.algo, test.password); },
/not supported in FIPS mode/); /not supported in FIPS mode/);
} else { } else {
var encrypt = crypto.createCipher(test.algo, test.password); const encrypt = crypto.createCipher(test.algo, test.password);
if (test.aad) if (test.aad)
encrypt.setAAD(Buffer.from(test.aad, 'hex')); encrypt.setAAD(Buffer.from(test.aad, 'hex'));
var hex = encrypt.update(test.plain, 'ascii', 'hex'); let hex = encrypt.update(test.plain, 'ascii', 'hex');
hex += encrypt.final('hex'); hex += encrypt.final('hex');
var auth_tag = encrypt.getAuthTag(); const auth_tag = encrypt.getAuthTag();
// only test basic encryption run if output is marked as tampered. // only test basic encryption run if output is marked as tampered.
if (!test.tampered) { if (!test.tampered) {
assert.equal(hex, test.ct); assert.strictEqual(hex, test.ct);
assert.equal(auth_tag.toString('hex'), test.tag); assert.strictEqual(auth_tag.toString('hex'), test.tag);
} }
} }
})(); }
(function() { {
if (!test.password) return; if (!test.password) return;
if (common.hasFipsCrypto) { if (common.hasFipsCrypto) {
assert.throws(() => { crypto.createDecipher(test.algo, test.password); }, assert.throws(() => { crypto.createDecipher(test.algo, test.password); },
/not supported in FIPS mode/); /not supported in FIPS mode/);
} else { } else {
var decrypt = crypto.createDecipher(test.algo, test.password); const decrypt = crypto.createDecipher(test.algo, test.password);
decrypt.setAuthTag(Buffer.from(test.tag, 'hex')); decrypt.setAuthTag(Buffer.from(test.tag, 'hex'));
if (test.aad) if (test.aad)
decrypt.setAAD(Buffer.from(test.aad, 'hex')); decrypt.setAAD(Buffer.from(test.aad, 'hex'));
var msg = decrypt.update(test.ct, 'hex', 'ascii'); let msg = decrypt.update(test.ct, 'hex', 'ascii');
if (!test.tampered) { if (!test.tampered) {
msg += decrypt.final('ascii'); msg += decrypt.final('ascii');
assert.equal(msg, test.plain); assert.strictEqual(msg, test.plain);
} else { } else {
// assert that final throws if input data could not be verified! // assert that final throws if input data could not be verified!
assert.throws(function() { decrypt.final('ascii'); }, / auth/); assert.throws(function() { decrypt.final('ascii'); }, / auth/);
} }
} }
})(); }
// after normal operation, test some incorrect ways of calling the API: // after normal operation, test some incorrect ways of calling the API:
// it's most certainly enough to run these tests with one algorithm only. // it's most certainly enough to run these tests with one algorithm only.
@ -407,41 +407,41 @@ for (var i in TEST_CASES) {
continue; continue;
} }
(function() { {
// non-authenticating mode: // non-authenticating mode:
var encrypt = crypto.createCipheriv('aes-128-cbc', const encrypt = crypto.createCipheriv('aes-128-cbc',
'ipxp9a6i1Mb4USb4', '6fKjEjR3Vl30EUYC'); 'ipxp9a6i1Mb4USb4', '6fKjEjR3Vl30EUYC');
encrypt.update('blah', 'ascii'); encrypt.update('blah', 'ascii');
encrypt.final(); encrypt.final();
assert.throws(() => { encrypt.getAuthTag(); }, / state/); assert.throws(() => { encrypt.getAuthTag(); }, / state/);
assert.throws(() => { encrypt.setAAD(Buffer.from('123', 'ascii')); }, assert.throws(() => { encrypt.setAAD(Buffer.from('123', 'ascii')); },
/ state/); / state/);
})(); }
(function() { {
// trying to get tag before inputting all data: // trying to get tag before inputting all data:
var encrypt = crypto.createCipheriv(test.algo, const encrypt = crypto.createCipheriv(test.algo,
Buffer.from(test.key, 'hex'), Buffer.from(test.iv, 'hex')); Buffer.from(test.key, 'hex'), Buffer.from(test.iv, 'hex'));
encrypt.update('blah', 'ascii'); encrypt.update('blah', 'ascii');
assert.throws(function() { encrypt.getAuthTag(); }, / state/); assert.throws(function() { encrypt.getAuthTag(); }, / state/);
})(); }
(function() { {
// trying to set tag on encryption object: // trying to set tag on encryption object:
var encrypt = crypto.createCipheriv(test.algo, const encrypt = crypto.createCipheriv(test.algo,
Buffer.from(test.key, 'hex'), Buffer.from(test.iv, 'hex')); Buffer.from(test.key, 'hex'), Buffer.from(test.iv, 'hex'));
assert.throws(() => { encrypt.setAuthTag(Buffer.from(test.tag, 'hex')); }, assert.throws(() => { encrypt.setAuthTag(Buffer.from(test.tag, 'hex')); },
/ state/); / state/);
})(); }
(function() { {
// trying to read tag from decryption object: // trying to read tag from decryption object:
var decrypt = crypto.createDecipheriv(test.algo, const decrypt = crypto.createDecipheriv(test.algo,
Buffer.from(test.key, 'hex'), Buffer.from(test.iv, 'hex')); Buffer.from(test.key, 'hex'), Buffer.from(test.iv, 'hex'));
assert.throws(function() { decrypt.getAuthTag(); }, / state/); assert.throws(function() { decrypt.getAuthTag(); }, / state/);
})(); }
(function() { {
// trying to create cipher with incorrect IV length // trying to create cipher with incorrect IV length
assert.throws(function() { assert.throws(function() {
crypto.createCipheriv( crypto.createCipheriv(
@ -450,5 +450,5 @@ for (var i in TEST_CASES) {
Buffer.alloc(0) Buffer.alloc(0)
); );
}, /Invalid IV length/); }, /Invalid IV length/);
})(); }
} }

View File

@ -580,58 +580,58 @@ assert.strictEqual(rsaVerify.verify(rsaPubPem, rsaSignature, 'hex'), true);
// //
// Test RSA signing and verification // Test RSA signing and verification
// //
(function() { {
var privateKey = fs.readFileSync( const privateKey = fs.readFileSync(
common.fixturesDir + '/test_rsa_privkey_2.pem'); common.fixturesDir + '/test_rsa_privkey_2.pem');
var publicKey = fs.readFileSync( const publicKey = fs.readFileSync(
common.fixturesDir + '/test_rsa_pubkey_2.pem'); common.fixturesDir + '/test_rsa_pubkey_2.pem');
var input = 'I AM THE WALRUS'; const input = 'I AM THE WALRUS';
var signature = const signature =
'79d59d34f56d0e94aa6a3e306882b52ed4191f07521f25f505a078dc2f89' + '79d59d34f56d0e94aa6a3e306882b52ed4191f07521f25f505a078dc2f89' +
'396e0c8ac89e996fde5717f4cb89199d8fec249961fcb07b74cd3d2a4ffa' + '396e0c8ac89e996fde5717f4cb89199d8fec249961fcb07b74cd3d2a4ffa' +
'235417b69618e4bcd76b97e29975b7ce862299410e1b522a328e44ac9bb2' + '235417b69618e4bcd76b97e29975b7ce862299410e1b522a328e44ac9bb2' +
'8195e0268da7eda23d9825ac43c724e86ceeee0d0d4465678652ccaf6501' + '8195e0268da7eda23d9825ac43c724e86ceeee0d0d4465678652ccaf6501' +
'0ddfb299bedeb1ad'; '0ddfb299bedeb1ad';
var sign = crypto.createSign('RSA-SHA256'); const sign = crypto.createSign('RSA-SHA256');
sign.update(input); sign.update(input);
var output = sign.sign(privateKey, 'hex'); const output = sign.sign(privateKey, 'hex');
assert.equal(output, signature); assert.strictEqual(output, signature);
var verify = crypto.createVerify('RSA-SHA256'); const verify = crypto.createVerify('RSA-SHA256');
verify.update(input); verify.update(input);
assert.strictEqual(verify.verify(publicKey, signature, 'hex'), true); assert.strictEqual(verify.verify(publicKey, signature, 'hex'), true);
})(); }
// //
// Test DSA signing and verification // Test DSA signing and verification
// //
(function() { {
var privateKey = fs.readFileSync( const privateKey = fs.readFileSync(
common.fixturesDir + '/test_dsa_privkey.pem'); common.fixturesDir + '/test_dsa_privkey.pem');
var publicKey = fs.readFileSync( const publicKey = fs.readFileSync(
common.fixturesDir + '/test_dsa_pubkey.pem'); common.fixturesDir + '/test_dsa_pubkey.pem');
var input = 'I AM THE WALRUS'; const input = 'I AM THE WALRUS';
// DSA signatures vary across runs so there is no static string to verify // DSA signatures vary across runs so there is no static string to verify
// against // against
var sign = crypto.createSign('DSS1'); const sign = crypto.createSign('DSS1');
sign.update(input); sign.update(input);
var signature = sign.sign(privateKey, 'hex'); const signature = sign.sign(privateKey, 'hex');
var verify = crypto.createVerify('DSS1'); const verify = crypto.createVerify('DSS1');
verify.update(input); verify.update(input);
assert.strictEqual(verify.verify(publicKey, signature, 'hex'), true); assert.strictEqual(verify.verify(publicKey, signature, 'hex'), true);
})(); }
// //

View File

@ -73,35 +73,35 @@ testCipher2('0123456789abcdef');
testCipher2(Buffer.from('0123456789abcdef')); testCipher2(Buffer.from('0123456789abcdef'));
// Base64 padding regression test, see #4837. // Base64 padding regression test, see #4837.
(function() { {
var c = crypto.createCipher('aes-256-cbc', 'secret'); const c = crypto.createCipher('aes-256-cbc', 'secret');
var s = c.update('test', 'utf8', 'base64') + c.final('base64'); const s = c.update('test', 'utf8', 'base64') + c.final('base64');
assert.equal(s, '375oxUQCIocvxmC5At+rvA=='); assert.strictEqual(s, '375oxUQCIocvxmC5At+rvA==');
})(); }
// Calling Cipher.final() or Decipher.final() twice should error but // Calling Cipher.final() or Decipher.final() twice should error but
// not assert. See #4886. // not assert. See #4886.
(function() { {
var c = crypto.createCipher('aes-256-cbc', 'secret'); const c = crypto.createCipher('aes-256-cbc', 'secret');
try { c.final('xxx'); } catch (e) { /* Ignore. */ } try { c.final('xxx'); } catch (e) { /* Ignore. */ }
try { c.final('xxx'); } catch (e) { /* Ignore. */ } try { c.final('xxx'); } catch (e) { /* Ignore. */ }
try { c.final('xxx'); } catch (e) { /* Ignore. */ } try { c.final('xxx'); } catch (e) { /* Ignore. */ }
var d = crypto.createDecipher('aes-256-cbc', 'secret'); const d = crypto.createDecipher('aes-256-cbc', 'secret');
try { d.final('xxx'); } catch (e) { /* Ignore. */ } try { d.final('xxx'); } catch (e) { /* Ignore. */ }
try { d.final('xxx'); } catch (e) { /* Ignore. */ } try { d.final('xxx'); } catch (e) { /* Ignore. */ }
try { d.final('xxx'); } catch (e) { /* Ignore. */ } try { d.final('xxx'); } catch (e) { /* Ignore. */ }
})(); }
// Regression test for #5482: string to Cipher#update() should not assert. // Regression test for #5482: string to Cipher#update() should not assert.
(function() { {
var c = crypto.createCipher('aes192', '0123456789abcdef'); const c = crypto.createCipher('aes192', '0123456789abcdef');
c.update('update'); c.update('update');
c.final(); c.final();
})(); }
// #5655 regression tests, 'utf-8' and 'utf8' are identical. // #5655 regression tests, 'utf-8' and 'utf8' are identical.
(function() { {
var c = crypto.createCipher('aes192', '0123456789abcdef'); let c = crypto.createCipher('aes192', '0123456789abcdef');
c.update('update', ''); // Defaults to "utf8". c.update('update', ''); // Defaults to "utf8".
c.final('utf-8'); // Should not throw. c.final('utf-8'); // Should not throw.
@ -112,4 +112,4 @@ testCipher2(Buffer.from('0123456789abcdef'));
c = crypto.createCipher('aes192', '0123456789abcdef'); c = crypto.createCipher('aes192', '0123456789abcdef');
c.update('update', 'utf-8'); c.update('update', 'utf-8');
c.final('utf8'); // Should not throw. c.final('utf8'); // Should not throw.
})(); }

View File

@ -57,19 +57,19 @@ var secret3 = dh3.computeSecret(key2, 'hex', 'base64');
assert.equal(secret1, secret3); assert.equal(secret1, secret3);
// Run this one twice to make sure that the dh3 clears its error properly // Run this one twice to make sure that the dh3 clears its error properly
(function() { {
var c = crypto.createDecipheriv('aes-128-ecb', crypto.randomBytes(16), ''); const c = crypto.createDecipheriv('aes-128-ecb', crypto.randomBytes(16), '');
assert.throws(function() { c.final('utf8'); }, /wrong final block length/); assert.throws(function() { c.final('utf8'); }, /wrong final block length/);
})(); }
assert.throws(function() { assert.throws(function() {
dh3.computeSecret(''); dh3.computeSecret('');
}, /key is too small/i); }, /key is too small/i);
(function() { {
var c = crypto.createDecipheriv('aes-128-ecb', crypto.randomBytes(16), ''); const c = crypto.createDecipheriv('aes-128-ecb', crypto.randomBytes(16), '');
assert.throws(function() { c.final('utf8'); }, /wrong final block length/); assert.throws(function() { c.final('utf8'); }, /wrong final block length/);
})(); }
// Create a shared using a DH group. // Create a shared using a DH group.
var alice = crypto.createDiffieHellmanGroup('modp5'); var alice = crypto.createDiffieHellmanGroup('modp5');

View File

@ -29,18 +29,18 @@ var b = Buffer.from(ucs2_control + ucs2_control, 'ucs2');
// //
// Test updating from birant data // Test updating from birant data
// //
(function() { {
var datum1 = b.slice(700000); const datum1 = b.slice(700000);
var hash1_converted = crypto.createHash('sha1') const hash1_converted = crypto.createHash('sha1')
.update(datum1.toString('base64'), 'base64') .update(datum1.toString('base64'), 'base64')
.digest('hex'); .digest('hex');
var hash1_direct = crypto.createHash('sha1').update(datum1).digest('hex'); const hash1_direct = crypto.createHash('sha1').update(datum1).digest('hex');
assert.equal(hash1_direct, hash1_converted, 'should hash the same.'); assert.strictEqual(hash1_direct, hash1_converted, 'should hash the same.');
var datum2 = b; const datum2 = b;
var hash2_converted = crypto.createHash('sha1') const hash2_converted = crypto.createHash('sha1')
.update(datum2.toString('base64'), 'base64') .update(datum2.toString('base64'), 'base64')
.digest('hex'); .digest('hex');
var hash2_direct = crypto.createHash('sha1').update(datum2).digest('hex'); const hash2_direct = crypto.createHash('sha1').update(datum2).digest('hex');
assert.equal(hash2_direct, hash2_converted, 'should hash the same.'); assert.strictEqual(hash2_direct, hash2_converted, 'should hash the same.');
})(); }

View File

@ -27,20 +27,20 @@ var dsaKeyPemEncrypted = fs.readFileSync(
common.fixturesDir + '/test_dsa_privkey_encrypted.pem', 'ascii'); common.fixturesDir + '/test_dsa_privkey_encrypted.pem', 'ascii');
// Test RSA encryption/decryption // Test RSA encryption/decryption
(function() { {
var input = 'I AM THE WALRUS'; const input = 'I AM THE WALRUS';
var bufferToEncrypt = Buffer.from(input); const bufferToEncrypt = Buffer.from(input);
var encryptedBuffer = crypto.publicEncrypt(rsaPubPem, bufferToEncrypt); let encryptedBuffer = crypto.publicEncrypt(rsaPubPem, bufferToEncrypt);
var decryptedBuffer = crypto.privateDecrypt(rsaKeyPem, encryptedBuffer); let decryptedBuffer = crypto.privateDecrypt(rsaKeyPem, encryptedBuffer);
assert.equal(input, decryptedBuffer.toString()); assert.strictEqual(input, decryptedBuffer.toString());
var decryptedBufferWithPassword = crypto.privateDecrypt({ let decryptedBufferWithPassword = crypto.privateDecrypt({
key: rsaKeyPemEncrypted, key: rsaKeyPemEncrypted,
passphrase: 'password' passphrase: 'password'
}, encryptedBuffer); }, encryptedBuffer);
assert.equal(input, decryptedBufferWithPassword.toString()); assert.strictEqual(input, decryptedBufferWithPassword.toString());
encryptedBuffer = crypto.publicEncrypt({ encryptedBuffer = crypto.publicEncrypt({
key: rsaKeyPemEncrypted, key: rsaKeyPemEncrypted,
@ -51,7 +51,7 @@ var dsaKeyPemEncrypted = fs.readFileSync(
key: rsaKeyPemEncrypted, key: rsaKeyPemEncrypted,
passphrase: 'password' passphrase: 'password'
}, encryptedBuffer); }, encryptedBuffer);
assert.equal(input, decryptedBufferWithPassword.toString()); assert.strictEqual(input, decryptedBufferWithPassword.toString());
encryptedBuffer = crypto.privateEncrypt({ encryptedBuffer = crypto.privateEncrypt({
key: rsaKeyPemEncrypted, key: rsaKeyPemEncrypted,
@ -62,22 +62,22 @@ var dsaKeyPemEncrypted = fs.readFileSync(
key: rsaKeyPemEncrypted, key: rsaKeyPemEncrypted,
passphrase: Buffer.from('password') passphrase: Buffer.from('password')
}, encryptedBuffer); }, encryptedBuffer);
assert.equal(input, decryptedBufferWithPassword.toString()); assert.strictEqual(input, decryptedBufferWithPassword.toString());
encryptedBuffer = crypto.publicEncrypt(certPem, bufferToEncrypt); encryptedBuffer = crypto.publicEncrypt(certPem, bufferToEncrypt);
decryptedBuffer = crypto.privateDecrypt(keyPem, encryptedBuffer); decryptedBuffer = crypto.privateDecrypt(keyPem, encryptedBuffer);
assert.equal(input, decryptedBuffer.toString()); assert.strictEqual(input, decryptedBuffer.toString());
encryptedBuffer = crypto.publicEncrypt(keyPem, bufferToEncrypt); encryptedBuffer = crypto.publicEncrypt(keyPem, bufferToEncrypt);
decryptedBuffer = crypto.privateDecrypt(keyPem, encryptedBuffer); decryptedBuffer = crypto.privateDecrypt(keyPem, encryptedBuffer);
assert.equal(input, decryptedBuffer.toString()); assert.strictEqual(input, decryptedBuffer.toString());
encryptedBuffer = crypto.privateEncrypt(keyPem, bufferToEncrypt); encryptedBuffer = crypto.privateEncrypt(keyPem, bufferToEncrypt);
decryptedBuffer = crypto.publicDecrypt(keyPem, encryptedBuffer); decryptedBuffer = crypto.publicDecrypt(keyPem, encryptedBuffer);
assert.equal(input, decryptedBuffer.toString()); assert.strictEqual(input, decryptedBuffer.toString());
assert.throws(function() { assert.throws(function() {
crypto.privateDecrypt({ crypto.privateDecrypt({
@ -104,7 +104,7 @@ var dsaKeyPemEncrypted = fs.readFileSync(
passphrase: [].concat.apply([], Buffer.from('password')) passphrase: [].concat.apply([], Buffer.from('password'))
}, encryptedBuffer); }, encryptedBuffer);
}); });
})(); }
function test_rsa(padding) { function test_rsa(padding) {
var input = Buffer.allocUnsafe(padding === 'RSA_NO_PADDING' ? 1024 / 8 : 32); var input = Buffer.allocUnsafe(padding === 'RSA_NO_PADDING' ? 1024 / 8 : 32);
@ -176,52 +176,52 @@ assert.throws(function() {
// //
// Test RSA signing and verification // Test RSA signing and verification
// //
(function() { {
var privateKey = fs.readFileSync( const privateKey = fs.readFileSync(
common.fixturesDir + '/test_rsa_privkey_2.pem'); common.fixturesDir + '/test_rsa_privkey_2.pem');
var publicKey = fs.readFileSync( const publicKey = fs.readFileSync(
common.fixturesDir + '/test_rsa_pubkey_2.pem'); common.fixturesDir + '/test_rsa_pubkey_2.pem');
var input = 'I AM THE WALRUS'; const input = 'I AM THE WALRUS';
var signature = const signature =
'79d59d34f56d0e94aa6a3e306882b52ed4191f07521f25f505a078dc2f89' + '79d59d34f56d0e94aa6a3e306882b52ed4191f07521f25f505a078dc2f89' +
'396e0c8ac89e996fde5717f4cb89199d8fec249961fcb07b74cd3d2a4ffa' + '396e0c8ac89e996fde5717f4cb89199d8fec249961fcb07b74cd3d2a4ffa' +
'235417b69618e4bcd76b97e29975b7ce862299410e1b522a328e44ac9bb2' + '235417b69618e4bcd76b97e29975b7ce862299410e1b522a328e44ac9bb2' +
'8195e0268da7eda23d9825ac43c724e86ceeee0d0d4465678652ccaf6501' + '8195e0268da7eda23d9825ac43c724e86ceeee0d0d4465678652ccaf6501' +
'0ddfb299bedeb1ad'; '0ddfb299bedeb1ad';
var sign = crypto.createSign('RSA-SHA256'); const sign = crypto.createSign('RSA-SHA256');
sign.update(input); sign.update(input);
var output = sign.sign(privateKey, 'hex'); const output = sign.sign(privateKey, 'hex');
assert.equal(output, signature); assert.strictEqual(output, signature);
var verify = crypto.createVerify('RSA-SHA256'); const verify = crypto.createVerify('RSA-SHA256');
verify.update(input); verify.update(input);
assert.strictEqual(verify.verify(publicKey, signature, 'hex'), true); assert.strictEqual(verify.verify(publicKey, signature, 'hex'), true);
})(); }
// //
// Test DSA signing and verification // Test DSA signing and verification
// //
(function() { {
var input = 'I AM THE WALRUS'; const input = 'I AM THE WALRUS';
// DSA signatures vary across runs so there is no static string to verify // DSA signatures vary across runs so there is no static string to verify
// against // against
var sign = crypto.createSign('DSS1'); const sign = crypto.createSign('DSS1');
sign.update(input); sign.update(input);
var signature = sign.sign(dsaKeyPem, 'hex'); const signature = sign.sign(dsaKeyPem, 'hex');
var verify = crypto.createVerify('DSS1'); const verify = crypto.createVerify('DSS1');
verify.update(input); verify.update(input);
assert.strictEqual(verify.verify(dsaPubPem, signature, 'hex'), true); assert.strictEqual(verify.verify(dsaPubPem, signature, 'hex'), true);
})(); }
// //

View File

@ -12,53 +12,47 @@ function unlink(pathname) {
common.refreshTmpDir(); common.refreshTmpDir();
(function() { {
var ncalls = 0; const pathname = common.tmpDir + '/test1';
var pathname = common.tmpDir + '/test1';
unlink(pathname); unlink(pathname);
fs.mkdir(pathname, function(err) { fs.mkdir(pathname, common.mustCall(function(err) {
assert.equal(err, null); assert.strictEqual(err, null);
assert.equal(common.fileExists(pathname), true); assert.strictEqual(common.fileExists(pathname), true);
ncalls++; }));
});
process.on('exit', function() { process.on('exit', function() {
unlink(pathname); unlink(pathname);
assert.equal(ncalls, 1);
}); });
})(); }
(function() { {
var ncalls = 0; const pathname = common.tmpDir + '/test2';
var pathname = common.tmpDir + '/test2';
unlink(pathname); unlink(pathname);
fs.mkdir(pathname, 0o777, function(err) { fs.mkdir(pathname, 0o777, common.mustCall(function(err) {
assert.equal(err, null); assert.equal(err, null);
assert.equal(common.fileExists(pathname), true); assert.equal(common.fileExists(pathname), true);
ncalls++; }));
});
process.on('exit', function() { process.on('exit', function() {
unlink(pathname); unlink(pathname);
assert.equal(ncalls, 1);
}); });
})(); }
(function() { {
var pathname = common.tmpDir + '/test3'; const pathname = common.tmpDir + '/test3';
unlink(pathname); unlink(pathname);
fs.mkdirSync(pathname); fs.mkdirSync(pathname);
var exists = common.fileExists(pathname); const exists = common.fileExists(pathname);
unlink(pathname); unlink(pathname);
assert.equal(exists, true); assert.strictEqual(exists, true);
})(); }
// Keep the event loop alive so the async mkdir() requests // Keep the event loop alive so the async mkdir() requests
// have a chance to run (since they don't ref the event loop). // have a chance to run (since they don't ref the event loop).

View File

@ -8,19 +8,19 @@ var filename = common.tmpDir + '/truncate-file.txt';
common.refreshTmpDir(); common.refreshTmpDir();
// Synchronous test. // Synchronous test.
(function() { {
fs.writeFileSync(filename, '0123456789'); fs.writeFileSync(filename, '0123456789');
assert.equal(fs.readFileSync(filename).toString(), '0123456789'); assert.strictEqual(fs.readFileSync(filename).toString(), '0123456789');
fs.truncateSync(filename, 5); fs.truncateSync(filename, 5);
assert.equal(fs.readFileSync(filename).toString(), '01234'); assert.strictEqual(fs.readFileSync(filename).toString(), '01234');
})(); }
// Asynchronous test. // Asynchronous test.
(function() { {
fs.writeFileSync(filename, '0123456789'); fs.writeFileSync(filename, '0123456789');
assert.equal(fs.readFileSync(filename).toString(), '0123456789'); assert.strictEqual(fs.readFileSync(filename).toString(), '0123456789');
fs.truncate(filename, 5, common.mustCall(function(err) { fs.truncate(filename, 5, common.mustCall(function(err) {
if (err) throw err; assert.ifError(err);
assert.equal(fs.readFileSync(filename).toString(), '01234'); assert.strictEqual(fs.readFileSync(filename).toString(), '01234');
})); }));
})(); }

View File

@ -6,19 +6,19 @@ var fs = require('fs');
common.refreshTmpDir(); common.refreshTmpDir();
(function() { {
var file = path.join(common.tmpDir, 'write-end-test0.txt'); const file = path.join(common.tmpDir, 'write-end-test0.txt');
var stream = fs.createWriteStream(file); const stream = fs.createWriteStream(file);
stream.end(); stream.end();
stream.on('close', common.mustCall(function() { })); stream.on('close', common.mustCall(function() { }));
})(); }
(function() { {
var file = path.join(common.tmpDir, 'write-end-test1.txt'); const file = path.join(common.tmpDir, 'write-end-test1.txt');
var stream = fs.createWriteStream(file); const stream = fs.createWriteStream(file);
stream.end('a\n', 'utf8'); stream.end('a\n', 'utf8');
stream.on('close', common.mustCall(function() { stream.on('close', common.mustCall(function() {
var content = fs.readFileSync(file, 'utf8'); const content = fs.readFileSync(file, 'utf8');
assert.equal(content, 'a\n'); assert.strictEqual(content, 'a\n');
})); }));
})(); }

View File

@ -8,7 +8,7 @@ var file = path.join(common.tmpDir, 'write.txt');
common.refreshTmpDir(); common.refreshTmpDir();
(function() { {
const stream = fs.WriteStream(file); const stream = fs.WriteStream(file);
const _fs_close = fs.close; const _fs_close = fs.close;
@ -17,15 +17,14 @@ common.refreshTmpDir();
fs.close = _fs_close; fs.close = _fs_close;
}; };
stream.destroy(); stream.destroy();
})(); }
(function() { {
var stream = fs.createWriteStream(file); const stream = fs.createWriteStream(file);
stream.on('drain', function() { stream.on('drain', function() {
assert.fail(null, null, '\'drain\' event must not be emitted before ' + common.fail('\'drain\' event must not be emitted before ' +
'stream.write() has been called at least once.'); 'stream.write() has been called at least once.');
}); });
stream.destroy(); stream.destroy();
})(); }

View File

@ -35,11 +35,11 @@ function test(handler, request_generator, response_validator) {
}); });
} }
(function() { {
function handler(req, res) { function handler(req, res) {
assert.equal('1.0', req.httpVersion); assert.strictEqual('1.0', req.httpVersion);
assert.equal(1, req.httpVersionMajor); assert.strictEqual(1, req.httpVersionMajor);
assert.equal(0, req.httpVersionMinor); assert.strictEqual(0, req.httpVersionMinor);
res.writeHead(200, {'Content-Type': 'text/plain'}); res.writeHead(200, {'Content-Type': 'text/plain'});
res.end(body); res.end(body);
} }
@ -49,25 +49,25 @@ function test(handler, request_generator, response_validator) {
} }
function response_validator(server_response, client_got_eof, timed_out) { function response_validator(server_response, client_got_eof, timed_out) {
var m = server_response.split('\r\n\r\n'); const m = server_response.split('\r\n\r\n');
assert.equal(m[1], body); assert.strictEqual(m[1], body);
assert.equal(true, client_got_eof); assert.strictEqual(true, client_got_eof);
assert.equal(false, timed_out); assert.strictEqual(false, timed_out);
} }
test(handler, request_generator, response_validator); test(handler, request_generator, response_validator);
})(); }
// //
// Don't send HTTP/1.1 status lines to HTTP/1.0 clients. // Don't send HTTP/1.1 status lines to HTTP/1.0 clients.
// //
// https://github.com/joyent/node/issues/1234 // https://github.com/joyent/node/issues/1234
// //
(function() { {
function handler(req, res) { function handler(req, res) {
assert.equal('1.0', req.httpVersion); assert.strictEqual('1.0', req.httpVersion);
assert.equal(1, req.httpVersionMajor); assert.strictEqual(1, req.httpVersionMajor);
assert.equal(0, req.httpVersionMinor); assert.strictEqual(0, req.httpVersionMinor);
res.sendDate = false; res.sendDate = false;
res.writeHead(200, {'Content-Type': 'text/plain'}); res.writeHead(200, {'Content-Type': 'text/plain'});
res.write('Hello, '); res._send(''); res.write('Hello, '); res._send('');
@ -85,25 +85,25 @@ function test(handler, request_generator, response_validator) {
} }
function response_validator(server_response, client_got_eof, timed_out) { function response_validator(server_response, client_got_eof, timed_out) {
var expected_response = 'HTTP/1.1 200 OK\r\n' + const expected_response = 'HTTP/1.1 200 OK\r\n' +
'Content-Type: text/plain\r\n' + 'Content-Type: text/plain\r\n' +
'Connection: close\r\n' + 'Connection: close\r\n' +
'\r\n' + '\r\n' +
'Hello, world!'; 'Hello, world!';
assert.equal(expected_response, server_response); assert.strictEqual(expected_response, server_response);
assert.equal(true, client_got_eof); assert.strictEqual(true, client_got_eof);
assert.equal(false, timed_out); assert.strictEqual(false, timed_out);
} }
test(handler, request_generator, response_validator); test(handler, request_generator, response_validator);
})(); }
(function() { {
function handler(req, res) { function handler(req, res) {
assert.equal('1.1', req.httpVersion); assert.strictEqual('1.1', req.httpVersion);
assert.equal(1, req.httpVersionMajor); assert.strictEqual(1, req.httpVersionMajor);
assert.equal(1, req.httpVersionMinor); assert.strictEqual(1, req.httpVersionMinor);
res.sendDate = false; res.sendDate = false;
res.writeHead(200, {'Content-Type': 'text/plain'}); res.writeHead(200, {'Content-Type': 'text/plain'});
res.write('Hello, '); res._send(''); res.write('Hello, '); res._send('');
@ -112,32 +112,32 @@ function test(handler, request_generator, response_validator) {
} }
function request_generator() { function request_generator() {
return ('GET / HTTP/1.1\r\n' + return 'GET / HTTP/1.1\r\n' +
'User-Agent: curl/7.19.7 (x86_64-pc-linux-gnu) libcurl/7.19.7 ' + 'User-Agent: curl/7.19.7 (x86_64-pc-linux-gnu) libcurl/7.19.7 ' +
'OpenSSL/0.9.8k zlib/1.2.3.3 libidn/1.15\r\n' + 'OpenSSL/0.9.8k zlib/1.2.3.3 libidn/1.15\r\n' +
'Connection: close\r\n' + 'Connection: close\r\n' +
'Host: 127.0.0.1:1337\r\n' + 'Host: 127.0.0.1:1337\r\n' +
'Accept: */*\r\n' + 'Accept: */*\r\n' +
'\r\n'); '\r\n';
} }
function response_validator(server_response, client_got_eof, timed_out) { function response_validator(server_response, client_got_eof, timed_out) {
var expected_response = 'HTTP/1.1 200 OK\r\n' + const expected_response = 'HTTP/1.1 200 OK\r\n' +
'Content-Type: text/plain\r\n' + 'Content-Type: text/plain\r\n' +
'Connection: close\r\n' + 'Connection: close\r\n' +
'Transfer-Encoding: chunked\r\n' + 'Transfer-Encoding: chunked\r\n' +
'\r\n' + '\r\n' +
'7\r\n' + '7\r\n' +
'Hello, \r\n' + 'Hello, \r\n' +
'6\r\n' + '6\r\n' +
'world!\r\n' + 'world!\r\n' +
'0\r\n' + '0\r\n' +
'\r\n'; '\r\n';
assert.equal(expected_response, server_response); assert.strictEqual(expected_response, server_response);
assert.equal(true, client_got_eof); assert.strictEqual(true, client_got_eof);
assert.equal(false, timed_out); assert.strictEqual(false, timed_out);
} }
test(handler, request_generator, response_validator); test(handler, request_generator, response_validator);
})(); }

View File

@ -72,21 +72,21 @@ function expectBody(expected) {
// //
// Simple request test. // Simple request test.
// //
(function() { {
var request = Buffer.from( const request = Buffer.from(
'GET /hello HTTP/1.1' + CRLF + 'GET /hello HTTP/1.1' + CRLF +
CRLF); CRLF);
var onHeadersComplete = function(versionMajor, versionMinor, headers, method, const onHeadersComplete = function(versionMajor, versionMinor, headers,
url, statusCode, statusMessage, upgrade, method, url, statusCode, statusMessage,
shouldKeepAlive) { upgrade, shouldKeepAlive) {
assert.equal(versionMajor, 1); assert.strictEqual(versionMajor, 1);
assert.equal(versionMinor, 1); assert.strictEqual(versionMinor, 1);
assert.equal(method, methods.indexOf('GET')); assert.strictEqual(method, methods.indexOf('GET'));
assert.equal(url || parser.url, '/hello'); assert.strictEqual(url || parser.url, '/hello');
}; };
var parser = newParser(REQUEST); const parser = newParser(REQUEST);
parser[kOnHeadersComplete] = mustCall(onHeadersComplete); parser[kOnHeadersComplete] = mustCall(onHeadersComplete);
parser.execute(request, 0, request.length); parser.execute(request, 0, request.length);
@ -104,72 +104,72 @@ function expectBody(expected) {
assert.throws(function() { assert.throws(function() {
parser.execute(request, 0, request.length); parser.execute(request, 0, request.length);
}, Error, 'hello world'); }, Error, 'hello world');
})(); }
// //
// Simple response test. // Simple response test.
// //
(function() { {
var request = Buffer.from( const request = Buffer.from(
'HTTP/1.1 200 OK' + CRLF + 'HTTP/1.1 200 OK' + CRLF +
'Content-Type: text/plain' + CRLF + 'Content-Type: text/plain' + CRLF +
'Content-Length: 4' + CRLF + 'Content-Length: 4' + CRLF +
CRLF + CRLF +
'pong'); 'pong');
var onHeadersComplete = function(versionMajor, versionMinor, headers, method, const onHeadersComplete = function(versionMajor, versionMinor, headers,
url, statusCode, statusMessage, upgrade, method, url, statusCode, statusMessage,
shouldKeepAlive) { upgrade, shouldKeepAlive) {
assert.equal(method, undefined); assert.strictEqual(method, undefined);
assert.equal(versionMajor, 1); assert.strictEqual(versionMajor, 1);
assert.equal(versionMinor, 1); assert.strictEqual(versionMinor, 1);
assert.equal(statusCode, 200); assert.strictEqual(statusCode, 200);
assert.equal(statusMessage, 'OK'); assert.strictEqual(statusMessage, 'OK');
}; };
var onBody = function(buf, start, len) { const onBody = function(buf, start, len) {
var body = '' + buf.slice(start, start + len); const body = '' + buf.slice(start, start + len);
assert.equal(body, 'pong'); assert.strictEqual(body, 'pong');
}; };
var parser = newParser(RESPONSE); const parser = newParser(RESPONSE);
parser[kOnHeadersComplete] = mustCall(onHeadersComplete); parser[kOnHeadersComplete] = mustCall(onHeadersComplete);
parser[kOnBody] = mustCall(onBody); parser[kOnBody] = mustCall(onBody);
parser.execute(request, 0, request.length); parser.execute(request, 0, request.length);
})(); }
// //
// Response with no headers. // Response with no headers.
// //
(function() { {
var request = Buffer.from( const request = Buffer.from(
'HTTP/1.0 200 Connection established' + CRLF + 'HTTP/1.0 200 Connection established' + CRLF +
CRLF); CRLF);
var onHeadersComplete = function(versionMajor, versionMinor, headers, method, const onHeadersComplete = function(versionMajor, versionMinor, headers,
url, statusCode, statusMessage, upgrade, method, url, statusCode, statusMessage,
shouldKeepAlive) { upgrade, shouldKeepAlive) {
assert.equal(versionMajor, 1); assert.strictEqual(versionMajor, 1);
assert.equal(versionMinor, 0); assert.strictEqual(versionMinor, 0);
assert.equal(method, undefined); assert.strictEqual(method, undefined);
assert.equal(statusCode, 200); assert.strictEqual(statusCode, 200);
assert.equal(statusMessage, 'Connection established'); assert.strictEqual(statusMessage, 'Connection established');
assert.deepStrictEqual(headers || parser.headers, []); assert.deepStrictEqual(headers || parser.headers, []);
}; };
var parser = newParser(RESPONSE); const parser = newParser(RESPONSE);
parser[kOnHeadersComplete] = mustCall(onHeadersComplete); parser[kOnHeadersComplete] = mustCall(onHeadersComplete);
parser.execute(request, 0, request.length); parser.execute(request, 0, request.length);
})(); }
// //
// Trailing headers. // Trailing headers.
// //
(function() { {
var request = Buffer.from( const request = Buffer.from(
'POST /it HTTP/1.1' + CRLF + 'POST /it HTTP/1.1' + CRLF +
'Transfer-Encoding: chunked' + CRLF + 'Transfer-Encoding: chunked' + CRLF +
CRLF + CRLF +
@ -180,139 +180,139 @@ function expectBody(expected) {
'Content-Type: text/plain' + CRLF + 'Content-Type: text/plain' + CRLF +
CRLF); CRLF);
var seen_body = false; let seen_body = false;
var onHeaders = function(headers, url) { const onHeaders = function(headers, url) {
assert.ok(seen_body); // trailers should come after the body assert.ok(seen_body); // trailers should come after the body
assert.deepStrictEqual(headers, assert.deepStrictEqual(headers,
['Vary', '*', 'Content-Type', 'text/plain']); ['Vary', '*', 'Content-Type', 'text/plain']);
}; };
var onHeadersComplete = function(versionMajor, versionMinor, headers, method, const onHeadersComplete = function(versionMajor, versionMinor, headers,
url, statusCode, statusMessage, upgrade, method, url, statusCode, statusMessage,
shouldKeepAlive) { upgrade, shouldKeepAlive) {
assert.equal(method, methods.indexOf('POST')); assert.strictEqual(method, methods.indexOf('POST'));
assert.equal(url || parser.url, '/it'); assert.strictEqual(url || parser.url, '/it');
assert.equal(versionMajor, 1); assert.strictEqual(versionMajor, 1);
assert.equal(versionMinor, 1); assert.strictEqual(versionMinor, 1);
// expect to see trailing headers now // expect to see trailing headers now
parser[kOnHeaders] = mustCall(onHeaders); parser[kOnHeaders] = mustCall(onHeaders);
}; };
var onBody = function(buf, start, len) { const onBody = function(buf, start, len) {
var body = '' + buf.slice(start, start + len); const body = '' + buf.slice(start, start + len);
assert.equal(body, 'ping'); assert.strictEqual(body, 'ping');
seen_body = true; seen_body = true;
}; };
var parser = newParser(REQUEST); const parser = newParser(REQUEST);
parser[kOnHeadersComplete] = mustCall(onHeadersComplete); parser[kOnHeadersComplete] = mustCall(onHeadersComplete);
parser[kOnBody] = mustCall(onBody); parser[kOnBody] = mustCall(onBody);
parser.execute(request, 0, request.length); parser.execute(request, 0, request.length);
})(); }
// //
// Test header ordering. // Test header ordering.
// //
(function() { {
var request = Buffer.from( const request = Buffer.from(
'GET / HTTP/1.0' + CRLF + 'GET / HTTP/1.0' + CRLF +
'X-Filler: 1337' + CRLF + 'X-Filler: 1337' + CRLF +
'X-Filler: 42' + CRLF + 'X-Filler: 42' + CRLF +
'X-Filler2: 42' + CRLF + 'X-Filler2: 42' + CRLF +
CRLF); CRLF);
var onHeadersComplete = function(versionMajor, versionMinor, headers, method, const onHeadersComplete = function(versionMajor, versionMinor, headers,
url, statusCode, statusMessage, upgrade, method, url, statusCode, statusMessage,
shouldKeepAlive) { upgrade, shouldKeepAlive) {
assert.equal(method, methods.indexOf('GET')); assert.strictEqual(method, methods.indexOf('GET'));
assert.equal(versionMajor, 1); assert.strictEqual(versionMajor, 1);
assert.equal(versionMinor, 0); assert.strictEqual(versionMinor, 0);
assert.deepStrictEqual( assert.deepStrictEqual(
headers || parser.headers, headers || parser.headers,
['X-Filler', '1337', 'X-Filler', '42', 'X-Filler2', '42']); ['X-Filler', '1337', 'X-Filler', '42', 'X-Filler2', '42']);
}; };
var parser = newParser(REQUEST); const parser = newParser(REQUEST);
parser[kOnHeadersComplete] = mustCall(onHeadersComplete); parser[kOnHeadersComplete] = mustCall(onHeadersComplete);
parser.execute(request, 0, request.length); parser.execute(request, 0, request.length);
})(); }
// //
// Test large number of headers // Test large number of headers
// //
(function() { {
// 256 X-Filler headers // 256 X-Filler headers
var lots_of_headers = 'X-Filler: 42' + CRLF; let lots_of_headers = 'X-Filler: 42' + CRLF;
lots_of_headers = lots_of_headers.repeat(256); lots_of_headers = lots_of_headers.repeat(256);
var request = Buffer.from( const request = Buffer.from(
'GET /foo/bar/baz?quux=42#1337 HTTP/1.0' + CRLF + 'GET /foo/bar/baz?quux=42#1337 HTTP/1.0' + CRLF +
lots_of_headers + lots_of_headers +
CRLF); CRLF);
var onHeadersComplete = function(versionMajor, versionMinor, headers, method, const onHeadersComplete = function(versionMajor, versionMinor, headers,
url, statusCode, statusMessage, upgrade, method, url, statusCode, statusMessage,
shouldKeepAlive) { upgrade, shouldKeepAlive) {
assert.equal(method, methods.indexOf('GET')); assert.strictEqual(method, methods.indexOf('GET'));
assert.equal(url || parser.url, '/foo/bar/baz?quux=42#1337'); assert.strictEqual(url || parser.url, '/foo/bar/baz?quux=42#1337');
assert.equal(versionMajor, 1); assert.strictEqual(versionMajor, 1);
assert.equal(versionMinor, 0); assert.strictEqual(versionMinor, 0);
headers = headers || parser.headers; headers = headers || parser.headers;
assert.equal(headers.length, 2 * 256); // 256 key/value pairs assert.strictEqual(headers.length, 2 * 256); // 256 key/value pairs
for (var i = 0; i < headers.length; i += 2) { for (let i = 0; i < headers.length; i += 2) {
assert.equal(headers[i], 'X-Filler'); assert.strictEqual(headers[i], 'X-Filler');
assert.equal(headers[i + 1], '42'); assert.strictEqual(headers[i + 1], '42');
} }
}; };
var parser = newParser(REQUEST); const parser = newParser(REQUEST);
parser[kOnHeadersComplete] = mustCall(onHeadersComplete); parser[kOnHeadersComplete] = mustCall(onHeadersComplete);
parser.execute(request, 0, request.length); parser.execute(request, 0, request.length);
})(); }
// //
// Test request body // Test request body
// //
(function() { {
var request = Buffer.from( const request = Buffer.from(
'POST /it HTTP/1.1' + CRLF + 'POST /it HTTP/1.1' + CRLF +
'Content-Type: application/x-www-form-urlencoded' + CRLF + 'Content-Type: application/x-www-form-urlencoded' + CRLF +
'Content-Length: 15' + CRLF + 'Content-Length: 15' + CRLF +
CRLF + CRLF +
'foo=42&bar=1337'); 'foo=42&bar=1337');
var onHeadersComplete = function(versionMajor, versionMinor, headers, method, const onHeadersComplete = function(versionMajor, versionMinor, headers,
url, statusCode, statusMessage, upgrade, method, url, statusCode, statusMessage,
shouldKeepAlive) { upgrade, shouldKeepAlive) {
assert.equal(method, methods.indexOf('POST')); assert.strictEqual(method, methods.indexOf('POST'));
assert.equal(url || parser.url, '/it'); assert.strictEqual(url || parser.url, '/it');
assert.equal(versionMajor, 1); assert.strictEqual(versionMajor, 1);
assert.equal(versionMinor, 1); assert.strictEqual(versionMinor, 1);
}; };
var onBody = function(buf, start, len) { const onBody = function(buf, start, len) {
var body = '' + buf.slice(start, start + len); const body = '' + buf.slice(start, start + len);
assert.equal(body, 'foo=42&bar=1337'); assert.strictEqual(body, 'foo=42&bar=1337');
}; };
var parser = newParser(REQUEST); const parser = newParser(REQUEST);
parser[kOnHeadersComplete] = mustCall(onHeadersComplete); parser[kOnHeadersComplete] = mustCall(onHeadersComplete);
parser[kOnBody] = mustCall(onBody); parser[kOnBody] = mustCall(onBody);
parser.execute(request, 0, request.length); parser.execute(request, 0, request.length);
})(); }
// //
// Test chunked request body // Test chunked request body
// //
(function() { {
var request = Buffer.from( const request = Buffer.from(
'POST /it HTTP/1.1' + CRLF + 'POST /it HTTP/1.1' + CRLF +
'Content-Type: text/plain' + CRLF + 'Content-Type: text/plain' + CRLF +
'Transfer-Encoding: chunked' + CRLF + 'Transfer-Encoding: chunked' + CRLF +
@ -325,35 +325,35 @@ function expectBody(expected) {
'1234567890' + CRLF + '1234567890' + CRLF +
'0' + CRLF); '0' + CRLF);
var onHeadersComplete = function(versionMajor, versionMinor, headers, method, const onHeadersComplete = function(versionMajor, versionMinor, headers,
url, statusCode, statusMessage, upgrade, method, url, statusCode, statusMessage,
shouldKeepAlive) { upgrade, shouldKeepAlive) {
assert.equal(method, methods.indexOf('POST')); assert.strictEqual(method, methods.indexOf('POST'));
assert.equal(url || parser.url, '/it'); assert.strictEqual(url || parser.url, '/it');
assert.equal(versionMajor, 1); assert.strictEqual(versionMajor, 1);
assert.equal(versionMinor, 1); assert.strictEqual(versionMinor, 1);
}; };
let body_part = 0; let body_part = 0;
const body_parts = ['123', '123456', '1234567890']; const body_parts = ['123', '123456', '1234567890'];
var onBody = function(buf, start, len) { const onBody = function(buf, start, len) {
var body = '' + buf.slice(start, start + len); const body = '' + buf.slice(start, start + len);
assert.equal(body, body_parts[body_part++]); assert.strictEqual(body, body_parts[body_part++]);
}; };
var parser = newParser(REQUEST); const parser = newParser(REQUEST);
parser[kOnHeadersComplete] = mustCall(onHeadersComplete); parser[kOnHeadersComplete] = mustCall(onHeadersComplete);
parser[kOnBody] = mustCall(onBody, body_parts.length); parser[kOnBody] = mustCall(onBody, body_parts.length);
parser.execute(request, 0, request.length); parser.execute(request, 0, request.length);
})(); }
// //
// Test chunked request body spread over multiple buffers (packets) // Test chunked request body spread over multiple buffers (packets)
// //
(function() { {
var request = Buffer.from( let request = Buffer.from(
'POST /it HTTP/1.1' + CRLF + 'POST /it HTTP/1.1' + CRLF +
'Content-Type: text/plain' + CRLF + 'Content-Type: text/plain' + CRLF +
'Transfer-Encoding: chunked' + CRLF + 'Transfer-Encoding: chunked' + CRLF +
@ -363,25 +363,25 @@ function expectBody(expected) {
'6' + CRLF + '6' + CRLF +
'123456' + CRLF); '123456' + CRLF);
var onHeadersComplete = function(versionMajor, versionMinor, headers, method, const onHeadersComplete = function(versionMajor, versionMinor, headers,
url, statusCode, statusMessage, upgrade, method, url, statusCode, statusMessage,
shouldKeepAlive) { upgrade, shouldKeepAlive) {
assert.equal(method, methods.indexOf('POST')); assert.strictEqual(method, methods.indexOf('POST'));
assert.equal(url || parser.url, '/it'); assert.strictEqual(url || parser.url, '/it');
assert.equal(versionMajor, 1); assert.strictEqual(versionMajor, 1);
assert.equal(versionMinor, 1); assert.strictEqual(versionMinor, 1);
}; };
let body_part = 0; let body_part = 0;
const body_parts = const body_parts =
['123', '123456', '123456789', '123456789ABC', '123456789ABCDEF']; ['123', '123456', '123456789', '123456789ABC', '123456789ABCDEF'];
var onBody = function(buf, start, len) { const onBody = function(buf, start, len) {
var body = '' + buf.slice(start, start + len); const body = '' + buf.slice(start, start + len);
assert.equal(body, body_parts[body_part++]); assert.strictEqual(body, body_parts[body_part++]);
}; };
var parser = newParser(REQUEST); const parser = newParser(REQUEST);
parser[kOnHeadersComplete] = mustCall(onHeadersComplete); parser[kOnHeadersComplete] = mustCall(onHeadersComplete);
parser[kOnBody] = mustCall(onBody, body_parts.length); parser[kOnBody] = mustCall(onBody, body_parts.length);
parser.execute(request, 0, request.length); parser.execute(request, 0, request.length);
@ -396,14 +396,14 @@ function expectBody(expected) {
'0' + CRLF); '0' + CRLF);
parser.execute(request, 0, request.length); parser.execute(request, 0, request.length);
})(); }
// //
// Stress test. // Stress test.
// //
(function() { {
var request = Buffer.from( const request = Buffer.from(
'POST /helpme HTTP/1.1' + CRLF + 'POST /helpme HTTP/1.1' + CRLF +
'Content-Type: text/plain' + CRLF + 'Content-Type: text/plain' + CRLF +
'Transfer-Encoding: chunked' + CRLF + 'Transfer-Encoding: chunked' + CRLF +
@ -421,30 +421,30 @@ function expectBody(expected) {
'0' + CRLF); '0' + CRLF);
function test(a, b) { function test(a, b) {
var onHeadersComplete = function(versionMajor, versionMinor, headers, const onHeadersComplete = function(versionMajor, versionMinor, headers,
method, url, statusCode, statusMessage, method, url, statusCode, statusMessage,
upgrade, shouldKeepAlive) { upgrade, shouldKeepAlive) {
assert.equal(method, methods.indexOf('POST')); assert.strictEqual(method, methods.indexOf('POST'));
assert.equal(url || parser.url, '/helpme'); assert.strictEqual(url || parser.url, '/helpme');
assert.equal(versionMajor, 1); assert.strictEqual(versionMajor, 1);
assert.equal(versionMinor, 1); assert.strictEqual(versionMinor, 1);
}; };
var expected_body = '123123456123456789123456789ABC123456789ABCDEF'; let expected_body = '123123456123456789123456789ABC123456789ABCDEF';
var onBody = function(buf, start, len) { const onBody = function(buf, start, len) {
var chunk = '' + buf.slice(start, start + len); const chunk = '' + buf.slice(start, start + len);
assert.equal(expected_body.indexOf(chunk), 0); assert.strictEqual(expected_body.indexOf(chunk), 0);
expected_body = expected_body.slice(chunk.length); expected_body = expected_body.slice(chunk.length);
}; };
var parser = newParser(REQUEST); const parser = newParser(REQUEST);
parser[kOnHeadersComplete] = mustCall(onHeadersComplete); parser[kOnHeadersComplete] = mustCall(onHeadersComplete);
parser[kOnBody] = onBody; parser[kOnBody] = onBody;
parser.execute(a, 0, a.length); parser.execute(a, 0, a.length);
parser.execute(b, 0, b.length); parser.execute(b, 0, b.length);
assert.equal(expected_body, ''); assert.strictEqual(expected_body, '');
} }
for (var i = 1; i < request.length - 1; ++i) { for (var i = 1; i < request.length - 1; ++i) {
@ -456,14 +456,14 @@ function expectBody(expected) {
JSON.stringify(b.toString())); JSON.stringify(b.toString()));
test(a, b); test(a, b);
} }
})(); }
// //
// Byte by byte test. // Byte by byte test.
// //
(function() { {
var request = Buffer.from( const request = Buffer.from(
'POST /it HTTP/1.1' + CRLF + 'POST /it HTTP/1.1' + CRLF +
'Content-Type: text/plain' + CRLF + 'Content-Type: text/plain' + CRLF +
'Transfer-Encoding: chunked' + CRLF + 'Transfer-Encoding: chunked' + CRLF +
@ -480,43 +480,43 @@ function expectBody(expected) {
'123456789ABCDEF' + CRLF + '123456789ABCDEF' + CRLF +
'0' + CRLF); '0' + CRLF);
var onHeadersComplete = function(versionMajor, versionMinor, headers, method, const onHeadersComplete = function(versionMajor, versionMinor, headers,
url, statusCode, statusMessage, upgrade, method, url, statusCode, statusMessage,
shouldKeepAlive) { upgrade, shouldKeepAlive) {
assert.equal(method, methods.indexOf('POST')); assert.strictEqual(method, methods.indexOf('POST'));
assert.equal(url || parser.url, '/it'); assert.strictEqual(url || parser.url, '/it');
assert.equal(versionMajor, 1); assert.strictEqual(versionMajor, 1);
assert.equal(versionMinor, 1); assert.strictEqual(versionMinor, 1);
assert.deepStrictEqual( assert.deepStrictEqual(
headers || parser.headers, headers || parser.headers,
['Content-Type', 'text/plain', 'Transfer-Encoding', 'chunked']); ['Content-Type', 'text/plain', 'Transfer-Encoding', 'chunked']);
}; };
var expected_body = '123123456123456789123456789ABC123456789ABCDEF'; let expected_body = '123123456123456789123456789ABC123456789ABCDEF';
var onBody = function(buf, start, len) { const onBody = function(buf, start, len) {
var chunk = '' + buf.slice(start, start + len); const chunk = '' + buf.slice(start, start + len);
assert.equal(expected_body.indexOf(chunk), 0); assert.strictEqual(expected_body.indexOf(chunk), 0);
expected_body = expected_body.slice(chunk.length); expected_body = expected_body.slice(chunk.length);
}; };
var parser = newParser(REQUEST); const parser = newParser(REQUEST);
parser[kOnHeadersComplete] = mustCall(onHeadersComplete); parser[kOnHeadersComplete] = mustCall(onHeadersComplete);
parser[kOnBody] = onBody; parser[kOnBody] = onBody;
for (var i = 0; i < request.length; ++i) { for (let i = 0; i < request.length; ++i) {
parser.execute(request, i, 1); parser.execute(request, i, 1);
} }
assert.equal(expected_body, ''); assert.strictEqual(expected_body, '');
})(); }
// //
// Test parser reinit sequence. // Test parser reinit sequence.
// //
(function() { {
var req1 = Buffer.from( const req1 = Buffer.from(
'PUT /this HTTP/1.1' + CRLF + 'PUT /this HTTP/1.1' + CRLF +
'Content-Type: text/plain' + CRLF + 'Content-Type: text/plain' + CRLF +
'Transfer-Encoding: chunked' + CRLF + 'Transfer-Encoding: chunked' + CRLF +
@ -525,16 +525,16 @@ function expectBody(expected) {
'ping' + CRLF + 'ping' + CRLF +
'0' + CRLF); '0' + CRLF);
var req2 = Buffer.from( const req2 = Buffer.from(
'POST /that HTTP/1.0' + CRLF + 'POST /that HTTP/1.0' + CRLF +
'Content-Type: text/plain' + CRLF + 'Content-Type: text/plain' + CRLF +
'Content-Length: 4' + CRLF + 'Content-Length: 4' + CRLF +
CRLF + CRLF +
'pong'); 'pong');
var onHeadersComplete1 = function(versionMajor, versionMinor, headers, method, const onHeadersComplete1 = function(versionMajor, versionMinor, headers,
url, statusCode, statusMessage, upgrade, method, url, statusCode, statusMessage,
shouldKeepAlive) { upgrade, shouldKeepAlive) {
assert.equal(method, methods.indexOf('PUT')); assert.equal(method, methods.indexOf('PUT'));
assert.equal(url, '/this'); assert.equal(url, '/this');
assert.equal(versionMajor, 1); assert.equal(versionMajor, 1);
@ -544,20 +544,20 @@ function expectBody(expected) {
['Content-Type', 'text/plain', 'Transfer-Encoding', 'chunked']); ['Content-Type', 'text/plain', 'Transfer-Encoding', 'chunked']);
}; };
var onHeadersComplete2 = function(versionMajor, versionMinor, headers, method, const onHeadersComplete2 = function(versionMajor, versionMinor, headers,
url, statusCode, statusMessage, upgrade, method, url, statusCode, statusMessage,
shouldKeepAlive) { upgrade, shouldKeepAlive) {
assert.equal(method, methods.indexOf('POST')); assert.strictEqual(method, methods.indexOf('POST'));
assert.equal(url, '/that'); assert.strictEqual(url, '/that');
assert.equal(versionMajor, 1); assert.strictEqual(versionMajor, 1);
assert.equal(versionMinor, 0); assert.strictEqual(versionMinor, 0);
assert.deepStrictEqual( assert.deepStrictEqual(
headers, headers,
['Content-Type', 'text/plain', 'Content-Length', '4'] ['Content-Type', 'text/plain', 'Content-Length', '4']
); );
}; };
var parser = newParser(REQUEST); const parser = newParser(REQUEST);
parser[kOnHeadersComplete] = onHeadersComplete1; parser[kOnHeadersComplete] = onHeadersComplete1;
parser[kOnBody] = expectBody('ping'); parser[kOnBody] = expectBody('ping');
parser.execute(req1, 0, req1.length); parser.execute(req1, 0, req1.length);
@ -566,7 +566,7 @@ function expectBody(expected) {
parser[kOnBody] = expectBody('pong'); parser[kOnBody] = expectBody('pong');
parser[kOnHeadersComplete] = onHeadersComplete2; parser[kOnHeadersComplete] = onHeadersComplete2;
parser.execute(req2, 0, req2.length); parser.execute(req2, 0, req2.length);
})(); }
// Test parser 'this' safety // Test parser 'this' safety
// https://github.com/joyent/node/issues/6690 // https://github.com/joyent/node/issues/6690

View File

@ -134,7 +134,7 @@ qsNoMungeTestCases.forEach(function(testCase) {
}); });
// test the nested qs-in-qs case // test the nested qs-in-qs case
(function() { {
const f = qs.parse('a=b&q=x%3Dy%26y%3Dz'); const f = qs.parse('a=b&q=x%3Dy%26y%3Dz');
check(f, createWithNoPrototype([ check(f, createWithNoPrototype([
{ key: 'a', value: 'b'}, { key: 'a', value: 'b'},
@ -147,10 +147,10 @@ qsNoMungeTestCases.forEach(function(testCase) {
{key: 'y', value: 'z' } {key: 'y', value: 'z' }
]); ]);
check(f.q, expectedInternal); check(f.q, expectedInternal);
})(); }
// nested in colon // nested in colon
(function() { {
const f = qs.parse('a:b;q:x%3Ay%3By%3Az', ';', ':'); const f = qs.parse('a:b;q:x%3Ay%3By%3Az', ';', ':');
check(f, createWithNoPrototype([ check(f, createWithNoPrototype([
{key: 'a', value: 'b'}, {key: 'a', value: 'b'},
@ -162,7 +162,7 @@ qsNoMungeTestCases.forEach(function(testCase) {
{key: 'y', value: 'z' } {key: 'y', value: 'z' }
]); ]);
check(f.q, expectedInternal); check(f.q, expectedInternal);
})(); }
// now test stringifying // now test stringifying

View File

@ -2,22 +2,22 @@
require('../common'); require('../common');
var assert = require('assert'); var assert = require('assert');
(function testInjectFakeModule() { {
var relativePath = '../fixtures/semicolon'; const relativePath = '../fixtures/semicolon';
var absolutePath = require.resolve(relativePath); const absolutePath = require.resolve(relativePath);
var fakeModule = {}; const fakeModule = {};
require.cache[absolutePath] = {exports: fakeModule}; require.cache[absolutePath] = {exports: fakeModule};
assert.strictEqual(require(relativePath), fakeModule); assert.strictEqual(require(relativePath), fakeModule);
})(); }
(function testInjectFakeNativeModule() { {
var relativePath = 'fs'; const relativePath = 'fs';
var fakeModule = {}; const fakeModule = {};
require.cache[relativePath] = {exports: fakeModule}; require.cache[relativePath] = {exports: fakeModule};
assert.strictEqual(require(relativePath), fakeModule); assert.strictEqual(require(relativePath), fakeModule);
})(); }

View File

@ -1,33 +1,33 @@
'use strict'; 'use strict';
require('../common'); const common = require('../common');
var assert = require('assert'); const assert = require('assert');
var Stream = require('stream').Stream; const Stream = require('stream').Stream;
(function testErrorListenerCatches() { {
var source = new Stream(); const source = new Stream();
var dest = new Stream(); const dest = new Stream();
source.pipe(dest); source.pipe(dest);
var gotErr = null; let gotErr = null;
source.on('error', function(err) { source.on('error', function(err) {
gotErr = err; gotErr = err;
}); });
var err = new Error('This stream turned into bacon.'); const err = new Error('This stream turned into bacon.');
source.emit('error', err); source.emit('error', err);
assert.strictEqual(gotErr, err); assert.strictEqual(gotErr, err);
})(); }
(function testErrorWithoutListenerThrows() { {
var source = new Stream(); const source = new Stream();
var dest = new Stream(); const dest = new Stream();
source.pipe(dest); source.pipe(dest);
var err = new Error('This stream turned into bacon.'); const err = new Error('This stream turned into bacon.');
var gotErr = null; let gotErr = null;
try { try {
source.emit('error', err); source.emit('error', err);
} catch (e) { } catch (e) {
@ -35,30 +35,23 @@ var Stream = require('stream').Stream;
} }
assert.strictEqual(gotErr, err); assert.strictEqual(gotErr, err);
})(); }
(function testErrorWithRemovedListenerThrows() { {
var R = Stream.Readable; const R = Stream.Readable;
var W = Stream.Writable; const W = Stream.Writable;
var r = new R(); const r = new R();
var w = new W(); const w = new W();
var removed = false; let removed = false;
var didTest = false;
process.on('exit', function() {
assert(didTest);
console.log('ok');
});
r._read = function() { r._read = function() {
setTimeout(function() { setTimeout(common.mustCall(function() {
assert(removed); assert(removed);
assert.throws(function() { assert.throws(function() {
w.emit('error', new Error('fail')); w.emit('error', new Error('fail'));
}); });
didTest = true; }));
});
}; };
w.on('error', myOnError); w.on('error', myOnError);
@ -69,41 +62,28 @@ var Stream = require('stream').Stream;
function myOnError(er) { function myOnError(er) {
throw new Error('this should not happen'); throw new Error('this should not happen');
} }
})(); }
(function testErrorWithRemovedListenerThrows() { {
var R = Stream.Readable; const R = Stream.Readable;
var W = Stream.Writable; const W = Stream.Writable;
var r = new R(); const r = new R();
var w = new W(); const w = new W();
var removed = false; let removed = false;
var didTest = false;
var caught = false;
process.on('exit', function() {
assert(didTest);
console.log('ok');
});
r._read = function() { r._read = function() {
setTimeout(function() { setTimeout(common.mustCall(function() {
assert(removed); assert(removed);
w.emit('error', new Error('fail')); w.emit('error', new Error('fail'));
didTest = true; }));
});
}; };
w.on('error', myOnError); w.on('error', common.mustCall(function(er) {}));
w._write = function() {}; w._write = function() {};
r.pipe(w); r.pipe(w);
// Removing some OTHER random listener should not do anything // Removing some OTHER random listener should not do anything
w.removeListener('error', function() {}); w.removeListener('error', function() {});
removed = true; removed = true;
}
function myOnError(er) {
assert(!caught);
caught = true;
}
})();

View File

@ -1,106 +1,64 @@
'use strict'; 'use strict';
require('../common'); const common = require('../common');
var assert = require('assert'); const assert = require('assert');
var Readable = require('stream').Readable; const Readable = require('stream').Readable;
(function first() { {
// First test, not reading when the readable is added. // First test, not reading when the readable is added.
// make sure that on('readable', ...) triggers a readable event. // make sure that on('readable', ...) triggers a readable event.
var r = new Readable({ const r = new Readable({
highWaterMark: 3 highWaterMark: 3
}); });
var _readCalled = false; r._read = common.fail;
r._read = function(n) {
_readCalled = true;
};
// This triggers a 'readable' event, which is lost. // This triggers a 'readable' event, which is lost.
r.push(Buffer.from('blerg')); r.push(Buffer.from('blerg'));
var caughtReadable = false;
setTimeout(function() { setTimeout(function() {
// we're testing what we think we are // we're testing what we think we are
assert(!r._readableState.reading); assert(!r._readableState.reading);
r.on('readable', function() { r.on('readable', common.mustCall(function() {}));
caughtReadable = true;
});
}); });
}
process.on('exit', function() { {
// we're testing what we think we are
assert(!_readCalled);
assert(caughtReadable);
console.log('ok 1');
});
})();
(function second() {
// second test, make sure that readable is re-emitted if there's // second test, make sure that readable is re-emitted if there's
// already a length, while it IS reading. // already a length, while it IS reading.
var r = new Readable({ const r = new Readable({
highWaterMark: 3 highWaterMark: 3
}); });
var _readCalled = false; r._read = common.mustCall(function(n) {});
r._read = function(n) {
_readCalled = true;
};
// This triggers a 'readable' event, which is lost. // This triggers a 'readable' event, which is lost.
r.push(Buffer.from('bl')); r.push(Buffer.from('bl'));
var caughtReadable = false;
setTimeout(function() { setTimeout(function() {
// assert we're testing what we think we are // assert we're testing what we think we are
assert(r._readableState.reading); assert(r._readableState.reading);
r.on('readable', function() { r.on('readable', common.mustCall(function() {}));
caughtReadable = true;
});
}); });
}
process.on('exit', function() { {
// we're testing what we think we are
assert(_readCalled);
assert(caughtReadable);
console.log('ok 2');
});
})();
(function third() {
// Third test, not reading when the stream has not passed // Third test, not reading when the stream has not passed
// the highWaterMark but *has* reached EOF. // the highWaterMark but *has* reached EOF.
var r = new Readable({ const r = new Readable({
highWaterMark: 30 highWaterMark: 30
}); });
var _readCalled = false; r._read = common.fail;
r._read = function(n) {
_readCalled = true;
};
// This triggers a 'readable' event, which is lost. // This triggers a 'readable' event, which is lost.
r.push(Buffer.from('blerg')); r.push(Buffer.from('blerg'));
r.push(null); r.push(null);
var caughtReadable = false;
setTimeout(function() { setTimeout(function() {
// assert we're testing what we think we are // assert we're testing what we think we are
assert(!r._readableState.reading); assert(!r._readableState.reading);
r.on('readable', function() { r.on('readable', common.mustCall(function() {}));
caughtReadable = true;
});
}); });
}
process.on('exit', function() {
// we're testing what we think we are
assert(!_readCalled);
assert(caughtReadable);
console.log('ok 3');
});
})();

View File

@ -17,24 +17,22 @@ MyWritable.prototype._write = function(chunk, encoding, callback) {
callback(); callback();
}; };
(function decodeStringsTrue() { {
var m = new MyWritable(function(isBuffer, type, enc) { const m = new MyWritable(function(isBuffer, type, enc) {
assert(isBuffer); assert(isBuffer);
assert.equal(type, 'object'); assert.strictEqual(type, 'object');
assert.equal(enc, 'buffer'); assert.strictEqual(enc, 'buffer');
console.log('ok - decoded string is decoded');
}, { decodeStrings: true }); }, { decodeStrings: true });
m.write('some-text', 'utf8'); m.write('some-text', 'utf8');
m.end(); m.end();
})(); }
(function decodeStringsFalse() { {
var m = new MyWritable(function(isBuffer, type, enc) { const m = new MyWritable(function(isBuffer, type, enc) {
assert(!isBuffer); assert(!isBuffer);
assert.equal(type, 'string'); assert.strictEqual(type, 'string');
assert.equal(enc, 'utf8'); assert.strictEqual(enc, 'utf8');
console.log('ok - un-decoded string is not decoded');
}, { decodeStrings: false }); }, { decodeStrings: false });
m.write('some-text', 'utf8'); m.write('some-text', 'utf8');
m.end(); m.end();
})(); }

View File

@ -3,77 +3,77 @@ require('../common');
var assert = require('assert'); var assert = require('assert');
var stream = require('stream'); var stream = require('stream');
(function testErrorListenerCatches() { {
var count = 1000; let count = 1000;
var source = new stream.Readable(); const source = new stream.Readable();
source._read = function(n) { source._read = function(n) {
n = Math.min(count, n); n = Math.min(count, n);
count -= n; count -= n;
source.push(Buffer.allocUnsafe(n)); source.push(Buffer.allocUnsafe(n));
}; };
var unpipedDest; let unpipedDest;
source.unpipe = function(dest) { source.unpipe = function(dest) {
unpipedDest = dest; unpipedDest = dest;
stream.Readable.prototype.unpipe.call(this, dest); stream.Readable.prototype.unpipe.call(this, dest);
}; };
var dest = new stream.Writable(); const dest = new stream.Writable();
dest._write = function(chunk, encoding, cb) { dest._write = function(chunk, encoding, cb) {
cb(); cb();
}; };
source.pipe(dest); source.pipe(dest);
var gotErr = null; let gotErr = null;
dest.on('error', function(err) { dest.on('error', function(err) {
gotErr = err; gotErr = err;
}); });
var unpipedSource; let unpipedSource;
dest.on('unpipe', function(src) { dest.on('unpipe', function(src) {
unpipedSource = src; unpipedSource = src;
}); });
var err = new Error('This stream turned into bacon.'); const err = new Error('This stream turned into bacon.');
dest.emit('error', err); dest.emit('error', err);
assert.strictEqual(gotErr, err); assert.strictEqual(gotErr, err);
assert.strictEqual(unpipedSource, source); assert.strictEqual(unpipedSource, source);
assert.strictEqual(unpipedDest, dest); assert.strictEqual(unpipedDest, dest);
})(); }
(function testErrorWithoutListenerThrows() { {
var count = 1000; let count = 1000;
var source = new stream.Readable(); const source = new stream.Readable();
source._read = function(n) { source._read = function(n) {
n = Math.min(count, n); n = Math.min(count, n);
count -= n; count -= n;
source.push(Buffer.allocUnsafe(n)); source.push(Buffer.allocUnsafe(n));
}; };
var unpipedDest; let unpipedDest;
source.unpipe = function(dest) { source.unpipe = function(dest) {
unpipedDest = dest; unpipedDest = dest;
stream.Readable.prototype.unpipe.call(this, dest); stream.Readable.prototype.unpipe.call(this, dest);
}; };
var dest = new stream.Writable(); const dest = new stream.Writable();
dest._write = function(chunk, encoding, cb) { dest._write = function(chunk, encoding, cb) {
cb(); cb();
}; };
source.pipe(dest); source.pipe(dest);
var unpipedSource; let unpipedSource;
dest.on('unpipe', function(src) { dest.on('unpipe', function(src) {
unpipedSource = src; unpipedSource = src;
}); });
var err = new Error('This stream turned into bacon.'); const err = new Error('This stream turned into bacon.');
var gotErr = null; let gotErr = null;
try { try {
dest.emit('error', err); dest.emit('error', err);
} catch (e) { } catch (e) {
@ -82,4 +82,4 @@ var stream = require('stream');
assert.strictEqual(gotErr, err); assert.strictEqual(gotErr, err);
assert.strictEqual(unpipedSource, source); assert.strictEqual(unpipedSource, source);
assert.strictEqual(unpipedDest, dest); assert.strictEqual(unpipedDest, dest);
})(); }

View File

@ -66,57 +66,57 @@ var RADIOS = 2;
var PRE_HALF_APEX = Math.ceil(EXTERN_APEX / 2) - RADIOS; var PRE_HALF_APEX = Math.ceil(EXTERN_APEX / 2) - RADIOS;
var PRE_3OF4_APEX = Math.ceil((EXTERN_APEX / 4) * 3) - RADIOS; var PRE_3OF4_APEX = Math.ceil((EXTERN_APEX / 4) * 3) - RADIOS;
(function() { {
for (var j = 0; j < RADIOS * 2; j += 1) { for (let j = 0; j < RADIOS * 2; j += 1) {
var datum = b; const datum = b;
var slice = datum.slice(0, PRE_HALF_APEX + j); const slice = datum.slice(0, PRE_HALF_APEX + j);
var slice2 = datum.slice(0, PRE_HALF_APEX + j + 2); const slice2 = datum.slice(0, PRE_HALF_APEX + j + 2);
var pumped_string = slice.toString('hex'); const pumped_string = slice.toString('hex');
var pumped_string2 = slice2.toString('hex'); const pumped_string2 = slice2.toString('hex');
var decoded = Buffer.from(pumped_string, 'hex'); const decoded = Buffer.from(pumped_string, 'hex');
// the string are the same? // the string are the same?
for (var k = 0; k < pumped_string.length; ++k) { for (let k = 0; k < pumped_string.length; ++k) {
assert.equal(pumped_string[k], pumped_string2[k]); assert.strictEqual(pumped_string[k], pumped_string2[k]);
} }
// the recoded buffer is the same? // the recoded buffer is the same?
for (var i = 0; i < decoded.length; ++i) { for (let i = 0; i < decoded.length; ++i) {
assert.equal(datum[i], decoded[i]); assert.strictEqual(datum[i], decoded[i]);
} }
} }
})(); }
(function() { {
for (var j = 0; j < RADIOS * 2; j += 1) { for (let j = 0; j < RADIOS * 2; j += 1) {
var datum = b; const datum = b;
var slice = datum.slice(0, PRE_3OF4_APEX + j); const slice = datum.slice(0, PRE_3OF4_APEX + j);
var slice2 = datum.slice(0, PRE_3OF4_APEX + j + 2); const slice2 = datum.slice(0, PRE_3OF4_APEX + j + 2);
var pumped_string = slice.toString('base64'); const pumped_string = slice.toString('base64');
var pumped_string2 = slice2.toString('base64'); const pumped_string2 = slice2.toString('base64');
var decoded = Buffer.from(pumped_string, 'base64'); const decoded = Buffer.from(pumped_string, 'base64');
// the string are the same? // the string are the same?
for (var k = 0; k < pumped_string.length - 3; ++k) { for (let k = 0; k < pumped_string.length - 3; ++k) {
assert.equal(pumped_string[k], pumped_string2[k]); assert.strictEqual(pumped_string[k], pumped_string2[k]);
} }
// the recoded buffer is the same? // the recoded buffer is the same?
for (var i = 0; i < decoded.length; ++i) { for (let i = 0; i < decoded.length; ++i) {
assert.equal(datum[i], decoded[i]); assert.strictEqual(datum[i], decoded[i]);
} }
} }
})(); }
// https://github.com/nodejs/node/issues/1024 // https://github.com/nodejs/node/issues/1024
(function() { {
var a = Array(1 << 20).join('x'); const a = Array(1 << 20).join('x');
var b = Buffer.from(a, 'ucs2').toString('ucs2'); const b = Buffer.from(a, 'ucs2').toString('ucs2');
var c = Buffer.from(b, 'utf8').toString('utf8'); const c = Buffer.from(b, 'utf8').toString('utf8');
assert.equal(a.length, b.length); assert.strictEqual(a.length, b.length);
assert.equal(b.length, c.length); assert.strictEqual(b.length, c.length);
assert.equal(a, b); assert.strictEqual(a, b);
assert.equal(b, c); assert.strictEqual(b, c);
})(); }

View File

@ -55,11 +55,11 @@ setInterval(function() {
}, SHORT_TIME); }, SHORT_TIME);
// Should not assert on args.Holder()->InternalFieldCount() > 0. See #4261. // Should not assert on args.Holder()->InternalFieldCount() > 0. See #4261.
(function() { {
var t = setInterval(function() {}, 1); const t = setInterval(function() {}, 1);
process.nextTick(t.unref.bind({})); process.nextTick(t.unref.bind({}));
process.nextTick(t.unref.bind(t)); process.nextTick(t.unref.bind(t));
})(); }
process.on('exit', function() { process.on('exit', function() {
assert.strictEqual(interval_fired, false, assert.strictEqual(interval_fired, false,

View File

@ -1,39 +1,32 @@
'use strict'; 'use strict';
require('../common'); const common = require('../common');
var assert = require('assert'); const assert = require('assert');
// https://github.com/joyent/node/issues/2079 - zero timeout drops extra args // https://github.com/joyent/node/issues/2079 - zero timeout drops extra args
(function() { {
var ncalled = 0; setTimeout(common.mustCall(f), 0, 'foo', 'bar', 'baz');
setTimeout(f, 0, 'foo', 'bar', 'baz');
setTimeout(function() {}, 0); setTimeout(function() {}, 0);
function f(a, b, c) { function f(a, b, c) {
assert.equal(a, 'foo'); assert.strictEqual(a, 'foo');
assert.equal(b, 'bar'); assert.strictEqual(b, 'bar');
assert.equal(c, 'baz'); assert.strictEqual(c, 'baz');
ncalled++;
} }
}
process.on('exit', function() { {
assert.equal(ncalled, 1); let ncalled = 0;
});
})();
(function() { const iv = setInterval(f, 0, 'foo', 'bar', 'baz');
var ncalled = 0;
var iv = setInterval(f, 0, 'foo', 'bar', 'baz');
function f(a, b, c) { function f(a, b, c) {
assert.equal(a, 'foo'); assert.strictEqual(a, 'foo');
assert.equal(b, 'bar'); assert.strictEqual(b, 'bar');
assert.equal(c, 'baz'); assert.strictEqual(c, 'baz');
if (++ncalled == 3) clearTimeout(iv); if (++ncalled == 3) clearTimeout(iv);
} }
process.on('exit', function() { process.on('exit', function() {
assert.equal(ncalled, 3); assert.strictEqual(ncalled, 3);
}); });
})(); }

View File

@ -13,37 +13,38 @@ var path = require('path');
// https://github.com/joyent/node/issues/1218 // https://github.com/joyent/node/issues/1218
// uncatchable exception on TLS connection error // uncatchable exception on TLS connection error
(function() { {
var cert = fs.readFileSync(path.join(common.fixturesDir, 'test_cert.pem')); const cert = fs.readFileSync(path.join(common.fixturesDir, 'test_cert.pem'));
var key = fs.readFileSync(path.join(common.fixturesDir, 'test_key.pem')); const key = fs.readFileSync(path.join(common.fixturesDir, 'test_key.pem'));
var errorEmitted = false; let errorEmitted = false;
process.on('exit', function() { process.on('exit', function() {
assert.ok(errorEmitted); assert.ok(errorEmitted);
}); });
var conn = tls.connect({cert: cert, key: key, port: common.PORT}, function() { const options = {cert: cert, key: key, port: common.PORT};
const conn = tls.connect(options, function() {
assert.ok(false); // callback should never be executed assert.ok(false); // callback should never be executed
}); });
conn.on('error', function() { conn.on('error', function() {
errorEmitted = true; errorEmitted = true;
}); });
})(); }
// SSL_accept/SSL_connect error handling // SSL_accept/SSL_connect error handling
(function() { {
var cert = fs.readFileSync(path.join(common.fixturesDir, 'test_cert.pem')); const cert = fs.readFileSync(path.join(common.fixturesDir, 'test_cert.pem'));
var key = fs.readFileSync(path.join(common.fixturesDir, 'test_key.pem')); const key = fs.readFileSync(path.join(common.fixturesDir, 'test_key.pem'));
var errorEmitted = false; let errorEmitted = false;
process.on('exit', function() { process.on('exit', function() {
assert.ok(errorEmitted); assert.ok(errorEmitted);
}); });
var conn = tls.connect({ const conn = tls.connect({
cert: cert, cert: cert,
key: key, key: key,
port: common.PORT, port: common.PORT,
@ -55,4 +56,4 @@ var path = require('path');
conn.on('error', function() { conn.on('error', function() {
errorEmitted = true; errorEmitted = true;
}); });
})(); }

View File

@ -48,11 +48,11 @@ assert.equal(util.format('%s:%s', 'foo', 'bar', 'baz'), 'foo:bar baz');
assert.equal(util.format('%%%s%%', 'hi'), '%hi%'); assert.equal(util.format('%%%s%%', 'hi'), '%hi%');
assert.equal(util.format('%%%s%%%%', 'hi'), '%hi%%'); assert.equal(util.format('%%%s%%%%', 'hi'), '%hi%%');
(function() { {
var o = {}; const o = {};
o.o = o; o.o = o;
assert.equal(util.format('%j', o), '[Circular]'); assert.equal(util.format('%j', o), '[Circular]');
})(); }
// Errors // Errors
const err = new Error('foo'); const err = new Error('foo');

View File

@ -31,9 +31,9 @@ assert.strictEqual(vm.runInDebugContext(undefined), undefined);
// See https://github.com/nodejs/node/issues/1190, accessing named interceptors // See https://github.com/nodejs/node/issues/1190, accessing named interceptors
// and accessors inside a debug event listener should not crash. // and accessors inside a debug event listener should not crash.
(function() { {
var Debug = vm.runInDebugContext('Debug'); const Debug = vm.runInDebugContext('Debug');
var breaks = 0; let breaks = 0;
function ondebugevent(evt, exc) { function ondebugevent(evt, exc) {
if (evt !== Debug.DebugEvent.Break) return; if (evt !== Debug.DebugEvent.Break) return;
@ -51,10 +51,10 @@ assert.strictEqual(vm.runInDebugContext(undefined), undefined);
assert.equal(breaks, 0); assert.equal(breaks, 0);
breakpoint(); breakpoint();
assert.equal(breaks, 1); assert.equal(breaks, 1);
})(); }
// Can set listeners and breakpoints on a single line file // Can set listeners and breakpoints on a single line file
(function() { {
const Debug = vm.runInDebugContext('Debug'); const Debug = vm.runInDebugContext('Debug');
const fn = require(common.fixturesDir + '/exports-function-with-param'); const fn = require(common.fixturesDir + '/exports-function-with-param');
let called = false; let called = false;
@ -69,7 +69,7 @@ assert.strictEqual(vm.runInDebugContext(undefined), undefined);
fn('foo'); fn('foo');
assert.strictEqual(Debug.showBreakPoints(fn), '(arg) { [B0]return arg; }'); assert.strictEqual(Debug.showBreakPoints(fn), '(arg) { [B0]return arg; }');
assert.strictEqual(called, true); assert.strictEqual(called, true);
})(); }
// See https://github.com/nodejs/node/issues/1190, fatal errors should not // See https://github.com/nodejs/node/issues/1190, fatal errors should not
// crash the process. // crash the process.

View File

@ -4,8 +4,8 @@ var assert = require('assert');
var zlib = require('zlib'); var zlib = require('zlib');
// Should raise an error, not trigger an assertion in src/node_zlib.cc // Should raise an error, not trigger an assertion in src/node_zlib.cc
(function() { {
var stream = zlib.createInflate(); const stream = zlib.createInflate();
stream.on('error', common.mustCall(function(err) { stream.on('error', common.mustCall(function(err) {
assert(/Missing dictionary/.test(err.message)); assert(/Missing dictionary/.test(err.message));
@ -13,11 +13,11 @@ var zlib = require('zlib');
// String "test" encoded with dictionary "dict". // String "test" encoded with dictionary "dict".
stream.write(Buffer.from([0x78, 0xBB, 0x04, 0x09, 0x01, 0xA5])); stream.write(Buffer.from([0x78, 0xBB, 0x04, 0x09, 0x01, 0xA5]));
})(); }
// Should raise an error, not trigger an assertion in src/node_zlib.cc // Should raise an error, not trigger an assertion in src/node_zlib.cc
(function() { {
var stream = zlib.createInflate({ dictionary: Buffer.from('fail') }); const stream = zlib.createInflate({ dictionary: Buffer.from('fail') });
stream.on('error', common.mustCall(function(err) { stream.on('error', common.mustCall(function(err) {
assert(/Bad dictionary/.test(err.message)); assert(/Bad dictionary/.test(err.message));
@ -25,4 +25,4 @@ var zlib = require('zlib');
// String "test" encoded with dictionary "dict". // String "test" encoded with dictionary "dict".
stream.write(Buffer.from([0x78, 0xBB, 0x04, 0x09, 0x01, 0xA5])); stream.write(Buffer.from([0x78, 0xBB, 0x04, 0x09, 0x01, 0xA5]));
})(); }

View File

@ -20,15 +20,15 @@ if (!common.opensslCli) {
// renegotiation limits to test // renegotiation limits to test
var LIMITS = [0, 1, 2, 3, 5, 10, 16]; var LIMITS = [0, 1, 2, 3, 5, 10, 16];
(function() { {
var n = 0; let n = 0;
function next() { function next() {
if (n >= LIMITS.length) return; if (n >= LIMITS.length) return;
tls.CLIENT_RENEG_LIMIT = LIMITS[n++]; tls.CLIENT_RENEG_LIMIT = LIMITS[n++];
test(next); test(next);
} }
next(); next();
})(); }
function test(next) { function test(next) {
var options = { var options = {

View File

@ -9,10 +9,11 @@ assert(typeof global.gc === 'function', 'Run this test with --expose-gc');
net.createServer(function() {}).listen(common.PORT); net.createServer(function() {}).listen(common.PORT);
var before = 0; var before = 0;
(function() { {
// 2**26 == 64M entries // 2**26 == 64M entries
global.gc(); global.gc();
for (var i = 0, junk = [0]; i < 26; ++i) junk = junk.concat(junk); let junk = [0];
for (let i = 0; i < 26; ++i) junk = junk.concat(junk);
before = process.memoryUsage().rss; before = process.memoryUsage().rss;
net.createConnection(common.PORT, '127.0.0.1', function() { net.createConnection(common.PORT, '127.0.0.1', function() {
@ -20,7 +21,7 @@ var before = 0;
setTimeout(done, 10); setTimeout(done, 10);
global.gc(); global.gc();
}); });
})(); }
function done() { function done() {
global.gc(); global.gc();

View File

@ -19,15 +19,15 @@ if (!common.opensslCli) {
// renegotiation limits to test // renegotiation limits to test
var LIMITS = [0, 1, 2, 3, 5, 10, 16]; var LIMITS = [0, 1, 2, 3, 5, 10, 16];
(function() { {
var n = 0; let n = 0;
function next() { function next() {
if (n >= LIMITS.length) return; if (n >= LIMITS.length) return;
tls.CLIENT_RENEG_LIMIT = LIMITS[n++]; tls.CLIENT_RENEG_LIMIT = LIMITS[n++];
test(next); test(next);
} }
next(); next();
})(); }
function test(next) { function test(next) {
var options = { var options = {

View File

@ -19,17 +19,19 @@ tls.createServer({
key: fs.readFileSync(common.fixturesDir + '/test_key.pem') key: fs.readFileSync(common.fixturesDir + '/test_key.pem')
}).listen(common.PORT); }).listen(common.PORT);
(function() { {
// 2**26 == 64M entries // 2**26 == 64M entries
for (var i = 0, junk = [0]; i < 26; ++i) junk = junk.concat(junk); let junk = [0];
var options = { rejectUnauthorized: false }; for (let i = 0; i < 26; ++i) junk = junk.concat(junk);
const options = { rejectUnauthorized: false };
tls.connect(common.PORT, '127.0.0.1', options, function() { tls.connect(common.PORT, '127.0.0.1', options, function() {
assert(junk.length != 0); // keep reference alive assert(junk.length != 0); // keep reference alive
setTimeout(done, 10); setTimeout(done, 10);
global.gc(); global.gc();
}); });
})(); }
function done() { function done() {
var before = process.memoryUsage().rss; var before = process.memoryUsage().rss;

View File

@ -70,8 +70,8 @@ assert.strictEqual(ret, msg + '\n',
} }
// Verify that stderr is not accessed when stdio = 'ignore' - GH #7966 // Verify that stderr is not accessed when stdio = 'ignore' - GH #7966
(function() { {
assert.throws(function() { assert.throws(function() {
execSync('exit -1', {stdio: 'ignore'}); execSync('exit -1', {stdio: 'ignore'});
}, /Command failed: exit -1/); }, /Command failed: exit -1/);
})(); }