test: adjust indentation for stricter linting

ESLint 4.x has stricter linting than previous versions. We are currently
using the legacy indentation rules in the test directory. This commit
changes the indentation of files to comply with the stricter 4.x linting
and enable stricter linting in the test directory.

PR-URL: https://github.com/nodejs/node/pull/14431
Reviewed-By: Refael Ackermann <refack@gmail.com>
Reviewed-By: Vse Mozhet Byt <vsemozhetbyt@gmail.com>
Reviewed-By: Trevor Norris <trev.norris@gmail.com>
This commit is contained in:
Rich Trott 2017-07-25 10:37:08 -07:00
parent 4f0b107334
commit aa6fac68da
101 changed files with 689 additions and 659 deletions

View File

@ -6,7 +6,7 @@ rules:
MemberExpression: off, MemberExpression: off,
ObjectExpression: first, ObjectExpression: first,
SwitchCase: 1}] SwitchCase: 1}]
indent-legacy: 0 indent-legacy: off
# Custom rules in tools/eslint-rules # Custom rules in tools/eslint-rules
require-buffer: error require-buffer: error

View File

@ -1,6 +1,16 @@
## Test-specific linter rules ## Test-specific linter rules
rules: rules:
# Stylistic Issues
# http://eslint.org/docs/rules/#stylistic-issues
indent: [error, 2, {ArrayExpression: first,
CallExpression: {arguments: first},
FunctionDeclaration: {parameters: first},
FunctionExpression: {parameters: first},
MemberExpression: off,
ObjectExpression: first,
SwitchCase: 1}]
indent-legacy: off
# ECMAScript 6 # ECMAScript 6
# http://eslint.org/docs/rules/#ecmascript-6 # http://eslint.org/docs/rules/#ecmascript-6
no-var: error no-var: error

View File

@ -12,7 +12,7 @@ if (process.argv[2] === 'child') {
} }
const p = child_process.spawnSync( const p = child_process.spawnSync(
process.execPath, [ '--napi-modules', __filename, 'child' ]); process.execPath, [ '--napi-modules', __filename, 'child' ]);
assert.ifError(p.error); assert.ifError(p.error);
assert.ok(p.stderr.toString().includes( assert.ok(p.stderr.toString().includes(
'FATAL ERROR: test_fatal::Test fatal message')); 'FATAL ERROR: test_fatal::Test fatal message'));

View File

@ -61,8 +61,10 @@ if (typeof Symbol !== 'undefined' && 'hasInstance' in Symbol &&
typeof Symbol.hasInstance === 'symbol') { typeof Symbol.hasInstance === 'symbol') {
function compareToNative(theObject, theConstructor) { function compareToNative(theObject, theConstructor) {
assert.strictEqual(addon.doInstanceOf(theObject, theConstructor), assert.strictEqual(
(theObject instanceof theConstructor)); addon.doInstanceOf(theObject, theConstructor),
(theObject instanceof theConstructor)
);
} }
function MyClass() {} function MyClass() {}

View File

@ -212,13 +212,14 @@ class ActivityCollector {
} }
exports = module.exports = function initHooks({ exports = module.exports = function initHooks({
oninit, oninit,
onbefore, onbefore,
onafter, onafter,
ondestroy, ondestroy,
allowNoInit, allowNoInit,
logid, logid,
logtype } = {}) { logtype
} = {}) {
return new ActivityCollector(process.hrtime(), { return new ActivityCollector(process.hrtime(), {
oninit, oninit,
onbefore, onbefore,

View File

@ -18,8 +18,8 @@ assert.throws(() => new AsyncResource('invalid_trigger_id', null),
/^RangeError: triggerAsyncId must be an unsigned integer$/); /^RangeError: triggerAsyncId must be an unsigned integer$/);
assert.strictEqual( assert.strictEqual(
new AsyncResource('default_trigger_id').triggerAsyncId(), new AsyncResource('default_trigger_id').triggerAsyncId(),
async_hooks.executionAsyncId() async_hooks.executionAsyncId()
); );
// create first custom event 'alcazares' with triggerAsyncId derived // create first custom event 'alcazares' with triggerAsyncId derived

View File

@ -41,12 +41,12 @@ process.on('exit', function() {
const as = hooks.activitiesOfTypes('TickObject'); const as = hooks.activitiesOfTypes('TickObject');
checkInvocations(as[0], { checkInvocations(as[0], {
init: 1, before: 1, after: 1, destroy: 1 init: 1, before: 1, after: 1, destroy: 1
}, 'when process exits'); }, 'when process exits');
checkInvocations(as[1], { checkInvocations(as[1], {
init: 1, before: 1, after: 1, destroy: 1 init: 1, before: 1, after: 1, destroy: 1
}, 'when process exits'); }, 'when process exits');
checkInvocations(as[2], { checkInvocations(as[2], {
init: 1, before: 1, after: 1, destroy: 1 init: 1, before: 1, after: 1, destroy: 1
}, 'when process exits'); }, 'when process exits');
}); });

View File

@ -100,53 +100,53 @@ function parseDNSPacket(buffer) {
.replace(/(.{4}(?!$))/g, '$1:'); .replace(/(.{4}(?!$))/g, '$1:');
break; break;
case types.TXT: case types.TXT:
{ {
let position = offset; let position = offset;
rr.entries = []; rr.entries = [];
while (position < offset + dataLength) { while (position < offset + dataLength) {
const txtLength = buffer[offset]; const txtLength = buffer[offset];
rr.entries.push(buffer.toString('utf8', rr.entries.push(buffer.toString('utf8',
position + 1, position + 1,
position + 1 + txtLength)); position + 1 + txtLength));
position += 1 + txtLength; position += 1 + txtLength;
}
assert.strictEqual(position, offset + dataLength);
break;
} }
assert.strictEqual(position, offset + dataLength);
break;
}
case types.MX: case types.MX:
{ {
rr.priority = buffer.readInt16BE(buffer, offset); rr.priority = buffer.readInt16BE(buffer, offset);
offset += 2; offset += 2;
const { nread, domain } = readDomainFromPacket(buffer, offset); const { nread, domain } = readDomainFromPacket(buffer, offset);
rr.exchange = domain; rr.exchange = domain;
assert.strictEqual(nread, dataLength); assert.strictEqual(nread, dataLength);
break; break;
} }
case types.NS: case types.NS:
case types.CNAME: case types.CNAME:
case types.PTR: case types.PTR:
{ {
const { nread, domain } = readDomainFromPacket(buffer, offset); const { nread, domain } = readDomainFromPacket(buffer, offset);
rr.value = domain; rr.value = domain;
assert.strictEqual(nread, dataLength); assert.strictEqual(nread, dataLength);
break; break;
} }
case types.SOA: case types.SOA:
{ {
const mname = readDomainFromPacket(buffer, offset); const mname = readDomainFromPacket(buffer, offset);
const rname = readDomainFromPacket(buffer, offset + mname.nread); const rname = readDomainFromPacket(buffer, offset + mname.nread);
rr.nsname = mname.domain; rr.nsname = mname.domain;
rr.hostmaster = rname.domain; rr.hostmaster = rname.domain;
const trailerOffset = offset + mname.nread + rname.nread; const trailerOffset = offset + mname.nread + rname.nread;
rr.serial = buffer.readUInt32BE(trailerOffset); rr.serial = buffer.readUInt32BE(trailerOffset);
rr.refresh = buffer.readUInt32BE(trailerOffset + 4); rr.refresh = buffer.readUInt32BE(trailerOffset + 4);
rr.retry = buffer.readUInt32BE(trailerOffset + 8); rr.retry = buffer.readUInt32BE(trailerOffset + 8);
rr.expire = buffer.readUInt32BE(trailerOffset + 12); rr.expire = buffer.readUInt32BE(trailerOffset + 12);
rr.minttl = buffer.readUInt32BE(trailerOffset + 16); rr.minttl = buffer.readUInt32BE(trailerOffset + 16);
assert.strictEqual(trailerOffset + 20, dataLength); assert.strictEqual(trailerOffset + 20, dataLength);
break; break;
} }
default: default:
throw new Error(`Unknown RR type ${rr.type}`); throw new Error(`Unknown RR type ${rr.type}`);
} }
@ -253,23 +253,23 @@ function writeDNSPacket(parsed) {
case 'NS': case 'NS':
case 'CNAME': case 'CNAME':
case 'PTR': case 'PTR':
{ {
const domain = writeDomainName(rr.exchange || rr.value); const domain = writeDomainName(rr.exchange || rr.value);
rdLengthBuf[0] += domain.length; rdLengthBuf[0] += domain.length;
buffers.push(domain); buffers.push(domain);
break; break;
} }
case 'SOA': case 'SOA':
{ {
const mname = writeDomainName(rr.nsname); const mname = writeDomainName(rr.nsname);
const rname = writeDomainName(rr.hostmaster); const rname = writeDomainName(rr.hostmaster);
rdLengthBuf[0] = mname.length + rname.length + 20; rdLengthBuf[0] = mname.length + rname.length + 20;
buffers.push(mname, rname); buffers.push(mname, rname);
buffers.push(new Uint32Array([ buffers.push(new Uint32Array([
rr.serial, rr.refresh, rr.retry, rr.expire, rr.minttl rr.serial, rr.refresh, rr.retry, rr.expire, rr.minttl
])); ]));
break; break;
} }
default: default:
throw new Error(`Unknown RR type ${rr.type}`); throw new Error(`Unknown RR type ${rr.type}`);
} }

View File

@ -44,8 +44,8 @@ function send(socket, message, id, callback) {
for (let i = 0; i < messageBuf.length; i++) for (let i = 0; i < messageBuf.length; i++)
messageBuf[i] = messageBuf[i] ^ (1 << (i % 4)); messageBuf[i] = messageBuf[i] ^ (1 << (i % 4));
socket.write( socket.write(
Buffer.concat([wsHeaderBuf.slice(0, maskOffset + 4), messageBuf]), Buffer.concat([wsHeaderBuf.slice(0, maskOffset + 4), messageBuf]),
callback); callback);
} }
function sendEnd(socket) { function sendEnd(socket) {
@ -74,7 +74,7 @@ function parseWSFrame(buffer, handler) {
if (buffer.length < bodyOffset + dataLen) if (buffer.length < bodyOffset + dataLen)
return 0; return 0;
const message = JSON.parse( const message = JSON.parse(
buffer.slice(bodyOffset, bodyOffset + dataLen).toString('utf8')); buffer.slice(bodyOffset, bodyOffset + dataLen).toString('utf8'));
if (DEBUG) if (DEBUG)
console.log('[received]', JSON.stringify(message)); console.log('[received]', JSON.stringify(message));
handler(message); handler(message);
@ -238,7 +238,7 @@ TestSession.prototype.sendInspectorCommands = function(commands) {
this.sendAll_(commands, () => { this.sendAll_(commands, () => {
timeoutId = setTimeout(() => { timeoutId = setTimeout(() => {
assert.fail(`Messages without response: ${ assert.fail(`Messages without response: ${
Object.keys(this.messages_).join(', ')}`); Object.keys(this.messages_).join(', ')}`);
}, TIMEOUT); }, TIMEOUT);
}); });
}); });
@ -282,7 +282,7 @@ TestSession.prototype.expectMessages = function(expects) {
if (!(expects instanceof Array)) expects = [ expects ]; if (!(expects instanceof Array)) expects = [ expects ];
const callback = this.createCallbackWithTimeout_( const callback = this.createCallbackWithTimeout_(
`Matching response was not received:\n${expects[0]}`); `Matching response was not received:\n${expects[0]}`);
this.messagefilter_ = (message) => { this.messagefilter_ = (message) => {
if (expects[0](message)) if (expects[0](message))
expects.shift(); expects.shift();
@ -296,8 +296,8 @@ TestSession.prototype.expectMessages = function(expects) {
TestSession.prototype.expectStderrOutput = function(regexp) { TestSession.prototype.expectStderrOutput = function(regexp) {
this.harness_.addStderrFilter( this.harness_.addStderrFilter(
regexp, regexp,
this.createCallbackWithTimeout_(`Timed out waiting for ${regexp}`)); this.createCallbackWithTimeout_(`Timed out waiting for ${regexp}`));
return this; return this;
}; };
@ -350,10 +350,10 @@ TestSession.prototype.assertClosed = function() {
TestSession.prototype.testHttpResponse = function(path, check) { TestSession.prototype.testHttpResponse = function(path, check) {
return this.enqueue((callback) => return this.enqueue((callback) =>
checkHttpResponse(null, this.harness_.port, path, (err, response) => { checkHttpResponse(null, this.harness_.port, path, (err, response) => {
check.call(this, err, response); check.call(this, err, response);
callback(); callback();
})); }));
}; };
@ -366,7 +366,7 @@ function Harness(port, childProcess) {
this.running_ = true; this.running_ = true;
childProcess.stdout.on('data', makeBufferingDataCallback( childProcess.stdout.on('data', makeBufferingDataCallback(
(line) => console.log('[out]', line))); (line) => console.log('[out]', line)));
childProcess.stderr.on('data', makeBufferingDataCallback((message) => { childProcess.stderr.on('data', makeBufferingDataCallback((message) => {

View File

@ -122,17 +122,17 @@ function testBreakpointOnStart(session) {
function testSetBreakpointAndResume(session) { function testSetBreakpointAndResume(session) {
console.log('[test]', 'Setting a breakpoint and verifying it is hit'); console.log('[test]', 'Setting a breakpoint and verifying it is hit');
const commands = [ const commands = [
{ 'method': 'Debugger.setBreakpointByUrl', { 'method': 'Debugger.setBreakpointByUrl',
'params': { 'lineNumber': 5, 'params': { 'lineNumber': 5,
'url': session.mainScriptPath, 'url': session.mainScriptPath,
'columnNumber': 0, 'columnNumber': 0,
'condition': '' 'condition': ''
} }
}, },
{ 'method': 'Debugger.resume' }, { 'method': 'Debugger.resume' },
[ { 'method': 'Debugger.getScriptSource', [ { 'method': 'Debugger.getScriptSource',
'params': { 'scriptId': session.mainScriptId } }, 'params': { 'scriptId': session.mainScriptId } },
expectMainScriptSource ], expectMainScriptSource ],
]; ];
session session
.sendInspectorCommands(commands) .sendInspectorCommands(commands)

View File

@ -6,8 +6,8 @@ const helper = require('./inspector-helper.js');
function shouldShutDown(session) { function shouldShutDown(session) {
session session
.sendInspectorCommands([ .sendInspectorCommands([
{ 'method': 'Debugger.enable' }, { 'method': 'Debugger.enable' },
{ 'method': 'Debugger.pause' }, { 'method': 'Debugger.pause' },
]) ])
.disconnect(true); .disconnect(true);
} }

View File

@ -11,9 +11,9 @@ const http = require('http');
const expected = '/café🐶'; const expected = '/café🐶';
assert.strictEqual( assert.strictEqual(
expected, expected,
'/caf\u{e9}\u{1f436}', '/caf\u{e9}\u{1f436}',
'Sanity check that string literal produced the expected string' 'Sanity check that string literal produced the expected string'
); );
const server = http.createServer(common.mustCall(function(req, res) { const server = http.createServer(common.mustCall(function(req, res) {

View File

@ -9,9 +9,9 @@ const assert = require('assert');
const vm = require('vm'); const vm = require('vm');
const handler = { const handler = {
getOwnPropertyDescriptor: (target, prop) => { getOwnPropertyDescriptor: (target, prop) => {
throw new Error('whoops'); throw new Error('whoops');
} }
}; };
const sandbox = new Proxy({ foo: 'bar' }, handler); const sandbox = new Proxy({ foo: 'bar' }, handler);
const context = vm.createContext(sandbox); const context = vm.createContext(sandbox);

View File

@ -19,7 +19,7 @@
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE. // USE OR OTHER DEALINGS IN THE SOFTWARE.
/* eslint-disable indent-legacy, no-tabs */ /* eslint-disable indent, no-tabs */
'use strict'; 'use strict';
require('../common'); require('../common');

View File

@ -501,10 +501,10 @@ assert.throws(() => {
let threw = false; let threw = false;
try { try {
assert.throws( assert.throws(
function() { function() {
throw ({}); // eslint-disable-line no-throw-literal throw ({}); // eslint-disable-line no-throw-literal
}, },
Array Array
); );
} catch (e) { } catch (e) {
threw = true; threw = true;

View File

@ -750,7 +750,7 @@ assert.strictEqual('<Buffer 81 a3 66 6f 6f a3 62 61 72>', x.inspect());
// Call .fill() first, stops valgrind warning about uninitialized memory reads. // Call .fill() first, stops valgrind warning about uninitialized memory reads.
Buffer.allocUnsafe(3.3).fill().toString(); Buffer.allocUnsafe(3.3).fill().toString();
// throws bad argument error in commit 43cb4ec // throws bad argument error in commit 43cb4ec
Buffer.alloc(3.3).fill().toString(); Buffer.alloc(3.3).fill().toString();
assert.strictEqual(Buffer.allocUnsafe(NaN).length, 0); assert.strictEqual(Buffer.allocUnsafe(NaN).length, 0);
assert.strictEqual(Buffer.allocUnsafe(3.3).length, 3); assert.strictEqual(Buffer.allocUnsafe(3.3).length, 3);

View File

@ -67,7 +67,7 @@ assert.throws(() => a.compare(b, 0, Infinity), oor);
assert.throws(() => a.compare(b, 0, 1, -1), oor); assert.throws(() => a.compare(b, 0, 1, -1), oor);
assert.throws(() => a.compare(b, -Infinity, Infinity), oor); assert.throws(() => a.compare(b, -Infinity, Infinity), oor);
assert.throws(() => a.compare(), common.expectsError({ assert.throws(() => a.compare(), common.expectsError({
code: 'ERR_INVALID_ARG_TYPE', code: 'ERR_INVALID_ARG_TYPE',
type: TypeError, type: TypeError,
message: 'The "target" argument must be one of type buffer or uint8Array' message: 'The "target" argument must be one of type buffer or uint8Array'
})); }));

View File

@ -29,9 +29,9 @@ assert.strictEqual(Buffer.compare(Buffer.alloc(0), Buffer.alloc(1)), -1);
assert.strictEqual(Buffer.compare(Buffer.alloc(1), Buffer.alloc(0)), 1); assert.strictEqual(Buffer.compare(Buffer.alloc(1), Buffer.alloc(0)), 1);
const errMsg = common.expectsError({ const errMsg = common.expectsError({
code: 'ERR_INVALID_ARG_TYPE', code: 'ERR_INVALID_ARG_TYPE',
type: TypeError, type: TypeError,
message: 'The "buf1", "buf2" arguments must be one of ' + message: 'The "buf1", "buf2" arguments must be one of ' +
'type buffer or uint8Array' 'type buffer or uint8Array'
}, 2); }, 2);
assert.throws(() => Buffer.compare(Buffer.alloc(1), 'abc'), errMsg); assert.throws(() => Buffer.compare(Buffer.alloc(1), 'abc'), errMsg);
@ -39,7 +39,7 @@ assert.throws(() => Buffer.compare(Buffer.alloc(1), 'abc'), errMsg);
assert.throws(() => Buffer.compare('abc', Buffer.alloc(1)), errMsg); assert.throws(() => Buffer.compare('abc', Buffer.alloc(1)), errMsg);
assert.throws(() => Buffer.alloc(1).compare('abc'), common.expectsError({ assert.throws(() => Buffer.alloc(1).compare('abc'), common.expectsError({
code: 'ERR_INVALID_ARG_TYPE', code: 'ERR_INVALID_ARG_TYPE',
type: TypeError, type: TypeError,
message: 'The "target" argument must be one of type buffer or uint8Array' message: 'The "target" argument must be one of type buffer or uint8Array'
})); }));

View File

@ -81,8 +81,8 @@ assert.deepStrictEqual(Buffer.concat([random10, empty, empty]), random10);
assert.deepStrictEqual(Buffer.concat([empty], 100), Buffer.alloc(100)); assert.deepStrictEqual(Buffer.concat([empty], 100), Buffer.alloc(100));
assert.deepStrictEqual(Buffer.concat([empty], 4096), Buffer.alloc(4096)); assert.deepStrictEqual(Buffer.concat([empty], 4096), Buffer.alloc(4096));
assert.deepStrictEqual( assert.deepStrictEqual(
Buffer.concat([random10], 40), Buffer.concat([random10], 40),
Buffer.concat([random10, Buffer.alloc(30)])); Buffer.concat([random10, Buffer.alloc(30)]));
assert.deepStrictEqual(Buffer.concat([new Uint8Array([0x41, 0x42]), assert.deepStrictEqual(Buffer.concat([new Uint8Array([0x41, 0x42]),
new Uint8Array([0x43, 0x44])]), new Uint8Array([0x43, 0x44])]),

View File

@ -431,36 +431,36 @@ assert.throws(() => {
{ code: undefined, type: RangeError, message: 'Index out of range' })); { code: undefined, type: RangeError, message: 'Index out of range' }));
assert.deepStrictEqual( assert.deepStrictEqual(
Buffer.allocUnsafeSlow(16).fill('ab', 'utf16le'), Buffer.allocUnsafeSlow(16).fill('ab', 'utf16le'),
Buffer.from('61006200610062006100620061006200', 'hex')); Buffer.from('61006200610062006100620061006200', 'hex'));
assert.deepStrictEqual( assert.deepStrictEqual(
Buffer.allocUnsafeSlow(15).fill('ab', 'utf16le'), Buffer.allocUnsafeSlow(15).fill('ab', 'utf16le'),
Buffer.from('610062006100620061006200610062', 'hex')); Buffer.from('610062006100620061006200610062', 'hex'));
assert.deepStrictEqual( assert.deepStrictEqual(
Buffer.allocUnsafeSlow(16).fill('ab', 'utf16le'), Buffer.allocUnsafeSlow(16).fill('ab', 'utf16le'),
Buffer.from('61006200610062006100620061006200', 'hex')); Buffer.from('61006200610062006100620061006200', 'hex'));
assert.deepStrictEqual( assert.deepStrictEqual(
Buffer.allocUnsafeSlow(16).fill('a', 'utf16le'), Buffer.allocUnsafeSlow(16).fill('a', 'utf16le'),
Buffer.from('61006100610061006100610061006100', 'hex')); Buffer.from('61006100610061006100610061006100', 'hex'));
assert.strictEqual( assert.strictEqual(
Buffer.allocUnsafeSlow(16).fill('a', 'utf16le').toString('utf16le'), Buffer.allocUnsafeSlow(16).fill('a', 'utf16le').toString('utf16le'),
'a'.repeat(8)); 'a'.repeat(8));
assert.strictEqual( assert.strictEqual(
Buffer.allocUnsafeSlow(16).fill('a', 'latin1').toString('latin1'), Buffer.allocUnsafeSlow(16).fill('a', 'latin1').toString('latin1'),
'a'.repeat(16)); 'a'.repeat(16));
assert.strictEqual( assert.strictEqual(
Buffer.allocUnsafeSlow(16).fill('a', 'utf8').toString('utf8'), Buffer.allocUnsafeSlow(16).fill('a', 'utf8').toString('utf8'),
'a'.repeat(16)); 'a'.repeat(16));
assert.strictEqual( assert.strictEqual(
Buffer.allocUnsafeSlow(16).fill('Љ', 'utf16le').toString('utf16le'), Buffer.allocUnsafeSlow(16).fill('Љ', 'utf16le').toString('utf16le'),
'Љ'.repeat(8)); 'Љ'.repeat(8));
assert.strictEqual( assert.strictEqual(
Buffer.allocUnsafeSlow(16).fill('Љ', 'latin1').toString('latin1'), Buffer.allocUnsafeSlow(16).fill('Љ', 'latin1').toString('latin1'),
'\t'.repeat(16)); '\t'.repeat(16));
assert.strictEqual( assert.strictEqual(
Buffer.allocUnsafeSlow(16).fill('Љ', 'utf8').toString('utf8'), Buffer.allocUnsafeSlow(16).fill('Љ', 'utf8').toString('utf8'),
'Љ'.repeat(8)); 'Љ'.repeat(8));

View File

@ -30,9 +30,10 @@ class MyBadPrimitive {
deepStrictEqual(Buffer.from(new String(checkString)), check); deepStrictEqual(Buffer.from(new String(checkString)), check);
deepStrictEqual(Buffer.from(new MyString()), check); deepStrictEqual(Buffer.from(new MyString()), check);
deepStrictEqual(Buffer.from(new MyPrimitive()), check); deepStrictEqual(Buffer.from(new MyPrimitive()), check);
deepStrictEqual(Buffer.from( deepStrictEqual(
runInNewContext('new String(checkString)', { checkString })), Buffer.from(runInNewContext('new String(checkString)', { checkString })),
check); check
);
[ [
{}, {},

View File

@ -154,11 +154,11 @@ assert(mixedByteStringUcs2.includes('\u03a3', 0, 'ucs2'));
assert(!mixedByteStringUcs2.includes('\u0396', 0, 'ucs2')); assert(!mixedByteStringUcs2.includes('\u0396', 0, 'ucs2'));
assert.ok( assert.ok(
mixedByteStringUcs2.includes(Buffer.from('bc', 'ucs2'), 0, 'ucs2')); mixedByteStringUcs2.includes(Buffer.from('bc', 'ucs2'), 0, 'ucs2'));
assert.ok( assert.ok(
mixedByteStringUcs2.includes(Buffer.from('\u03a3', 'ucs2'), 0, 'ucs2')); mixedByteStringUcs2.includes(Buffer.from('\u03a3', 'ucs2'), 0, 'ucs2'));
assert.ok( assert.ok(
!mixedByteStringUcs2.includes(Buffer.from('\u0396', 'ucs2'), 0, 'ucs2')); !mixedByteStringUcs2.includes(Buffer.from('\u0396', 'ucs2'), 0, 'ucs2'));
twoByteString = Buffer.from('\u039a\u0391\u03a3\u03a3\u0395', 'ucs2'); twoByteString = Buffer.from('\u039a\u0391\u03a3\u03a3\u0395', 'ucs2');
@ -208,7 +208,7 @@ assert(longBufferString.includes(pattern, 512), 'Long JABACABA..., Second J');
// Search for a non-ASCII string in a pure ASCII string. // Search for a non-ASCII string in a pure ASCII string.
const asciiString = Buffer.from( const asciiString = Buffer.from(
'arglebargleglopglyfarglebargleglopglyfarglebargleglopglyf'); 'arglebargleglopglyfarglebargleglopglyfarglebargleglopglyf');
assert(!asciiString.includes('\x2061')); assert(!asciiString.includes('\x2061'));
assert(asciiString.includes('leb', 0)); assert(asciiString.includes('leb', 0));
@ -263,11 +263,11 @@ for (let lengthIndex = 0; lengthIndex < lengths.length; lengthIndex++) {
const patternBufferUcs2 = const patternBufferUcs2 =
allCharsBufferUcs2.slice(index, index + length); allCharsBufferUcs2.slice(index, index + length);
assert.ok( assert.ok(
allCharsBufferUcs2.includes(patternBufferUcs2, 0, 'ucs2')); allCharsBufferUcs2.includes(patternBufferUcs2, 0, 'ucs2'));
const patternStringUcs2 = patternBufferUcs2.toString('ucs2'); const patternStringUcs2 = patternBufferUcs2.toString('ucs2');
assert.ok( assert.ok(
allCharsBufferUcs2.includes(patternStringUcs2, 0, 'ucs2')); allCharsBufferUcs2.includes(patternStringUcs2, 0, 'ucs2'));
} }
} }

View File

@ -198,11 +198,11 @@ assert.strictEqual(10, mixedByteStringUcs2.indexOf('\u03a3', 0, 'ucs2'));
assert.strictEqual(-1, mixedByteStringUcs2.indexOf('\u0396', 0, 'ucs2')); assert.strictEqual(-1, mixedByteStringUcs2.indexOf('\u0396', 0, 'ucs2'));
assert.strictEqual( assert.strictEqual(
6, mixedByteStringUcs2.indexOf(Buffer.from('bc', 'ucs2'), 0, 'ucs2')); 6, mixedByteStringUcs2.indexOf(Buffer.from('bc', 'ucs2'), 0, 'ucs2'));
assert.strictEqual( assert.strictEqual(
10, mixedByteStringUcs2.indexOf(Buffer.from('\u03a3', 'ucs2'), 0, 'ucs2')); 10, mixedByteStringUcs2.indexOf(Buffer.from('\u03a3', 'ucs2'), 0, 'ucs2'));
assert.strictEqual( assert.strictEqual(
-1, mixedByteStringUcs2.indexOf(Buffer.from('\u0396', 'ucs2'), 0, 'ucs2')); -1, mixedByteStringUcs2.indexOf(Buffer.from('\u0396', 'ucs2'), 0, 'ucs2'));
{ {
const twoByteString = Buffer.from('\u039a\u0391\u03a3\u03a3\u0395', 'ucs2'); const twoByteString = Buffer.from('\u039a\u0391\u03a3\u03a3\u0395', 'ucs2');
@ -222,13 +222,13 @@ assert.strictEqual(
// Test multi-char pattern // Test multi-char pattern
assert.strictEqual( assert.strictEqual(
0, twoByteString.indexOf('\u039a\u0391', 0, 'ucs2'), 'Lambda Alpha'); 0, twoByteString.indexOf('\u039a\u0391', 0, 'ucs2'), 'Lambda Alpha');
assert.strictEqual( assert.strictEqual(
2, twoByteString.indexOf('\u0391\u03a3', 0, 'ucs2'), 'Alpha Sigma'); 2, twoByteString.indexOf('\u0391\u03a3', 0, 'ucs2'), 'Alpha Sigma');
assert.strictEqual( assert.strictEqual(
4, twoByteString.indexOf('\u03a3\u03a3', 0, 'ucs2'), 'Sigma Sigma'); 4, twoByteString.indexOf('\u03a3\u03a3', 0, 'ucs2'), 'Sigma Sigma');
assert.strictEqual( assert.strictEqual(
6, twoByteString.indexOf('\u03a3\u0395', 0, 'ucs2'), 'Sigma Epsilon'); 6, twoByteString.indexOf('\u03a3\u0395', 0, 'ucs2'), 'Sigma Epsilon');
} }
const mixedByteStringUtf8 = Buffer.from('\u039a\u0391abc\u03a3\u03a3\u0395'); const mixedByteStringUtf8 = Buffer.from('\u039a\u0391abc\u03a3\u03a3\u0395');
@ -258,17 +258,17 @@ for (let i = 0; i < longBufferString.length - pattern.length; i += 7) {
assert.strictEqual(510, longBufferString.indexOf('AJABACA'), assert.strictEqual(510, longBufferString.indexOf('AJABACA'),
'Long AJABACA, First J'); 'Long AJABACA, First J');
assert.strictEqual( assert.strictEqual(
1534, longBufferString.indexOf('AJABACA', 511), 'Long AJABACA, Second J'); 1534, longBufferString.indexOf('AJABACA', 511), 'Long AJABACA, Second J');
pattern = 'JABACABADABACABA'; pattern = 'JABACABADABACABA';
assert.strictEqual( assert.strictEqual(
511, longBufferString.indexOf(pattern), 'Long JABACABA..., First J'); 511, longBufferString.indexOf(pattern), 'Long JABACABA..., First J');
assert.strictEqual( assert.strictEqual(
1535, longBufferString.indexOf(pattern, 512), 'Long JABACABA..., Second J'); 1535, longBufferString.indexOf(pattern, 512), 'Long JABACABA..., Second J');
// Search for a non-ASCII string in a pure ASCII string. // Search for a non-ASCII string in a pure ASCII string.
const asciiString = Buffer.from( const asciiString = Buffer.from(
'arglebargleglopglyfarglebargleglopglyfarglebargleglopglyf'); 'arglebargleglopglyfarglebargleglopglyfarglebargleglopglyf');
assert.strictEqual(-1, asciiString.indexOf('\x2061')); assert.strictEqual(-1, asciiString.indexOf('\x2061'));
assert.strictEqual(3, asciiString.indexOf('leb', 0)); assert.strictEqual(3, asciiString.indexOf('leb', 0));
@ -335,11 +335,11 @@ assert.strictEqual(Buffer.from('aaaaa').indexOf('b', 'ucs2'), -1);
const patternBufferUcs2 = const patternBufferUcs2 =
allCharsBufferUcs2.slice(index, index + length); allCharsBufferUcs2.slice(index, index + length);
assert.strictEqual( assert.strictEqual(
index, allCharsBufferUcs2.indexOf(patternBufferUcs2, 0, 'ucs2')); index, allCharsBufferUcs2.indexOf(patternBufferUcs2, 0, 'ucs2'));
const patternStringUcs2 = patternBufferUcs2.toString('ucs2'); const patternStringUcs2 = patternBufferUcs2.toString('ucs2');
assert.strictEqual( assert.strictEqual(
index, allCharsBufferUcs2.indexOf(patternStringUcs2, 0, 'ucs2')); index, allCharsBufferUcs2.indexOf(patternStringUcs2, 0, 'ucs2'));
} }
} }
} }

View File

@ -3,7 +3,8 @@
require('../common'); require('../common');
const assert = require('assert'); const assert = require('assert');
[ 'hex', [
'hex',
'utf8', 'utf8',
'utf-8', 'utf-8',
'ascii', 'ascii',
@ -13,11 +14,13 @@ const assert = require('assert');
'ucs2', 'ucs2',
'ucs-2', 'ucs-2',
'utf16le', 'utf16le',
'utf-16le' ].forEach((enc) => { 'utf-16le'
assert.strictEqual(Buffer.isEncoding(enc), true); ].forEach((enc) => {
}); assert.strictEqual(Buffer.isEncoding(enc), true);
});
[ 'utf9', [
'utf9',
'utf-7', 'utf-7',
'Unicode-FTW', 'Unicode-FTW',
'new gnu gun', 'new gnu gun',
@ -28,6 +31,7 @@ const assert = require('assert');
[], [],
1, 1,
0, 0,
-1 ].forEach((enc) => { -1
assert.strictEqual(Buffer.isEncoding(enc), false); ].forEach((enc) => {
}); assert.strictEqual(Buffer.isEncoding(enc), false);
});

View File

@ -4,8 +4,7 @@ const common = require('../common');
const assert = require('assert'); const assert = require('assert');
assert.throws(() => new Buffer(42, 'utf8'), common.expectsError({ assert.throws(() => new Buffer(42, 'utf8'), common.expectsError({
code: 'ERR_INVALID_ARG_TYPE', code: 'ERR_INVALID_ARG_TYPE',
type: TypeError, type: TypeError,
message: 'The "string" argument must be of type string. ' + message: 'The "string" argument must be of type string. Received type number'
'Received type number'
})); }));

View File

@ -14,9 +14,9 @@ function read(buff, funx, args, expected) {
); );
assert.doesNotThrow( assert.doesNotThrow(
() => assert.strictEqual(buff[funx](...args, true), expected), () => assert.strictEqual(buff[funx](...args, true), expected),
'noAssert does not change return value for valid ranges' 'noAssert does not change return value for valid ranges'
); );
} }

View File

@ -14,5 +14,5 @@ const noArgv0 = cp.spawnSync(process.execPath, [__filename, 'child']);
assert.strictEqual(noArgv0.stdout.toString().trim(), process.execPath); assert.strictEqual(noArgv0.stdout.toString().trim(), process.execPath);
const withArgv0 = cp.spawnSync(process.execPath, [__filename, 'child'], const withArgv0 = cp.spawnSync(process.execPath, [__filename, 'child'],
{ argv0: 'withArgv0' }); { argv0: 'withArgv0' });
assert.strictEqual(withArgv0.stdout.toString().trim(), 'withArgv0'); assert.strictEqual(withArgv0.stdout.toString().trim(), 'withArgv0');

View File

@ -38,7 +38,7 @@ switch (process.argv[2]) {
default: default:
const start = Date.now(); const start = Date.now();
const ret = spawnSync(process.execPath, [__filename, 'child'], const ret = spawnSync(process.execPath, [__filename, 'child'],
{ timeout: TIMER }); { timeout: TIMER });
assert.strictEqual(ret.error.errno, 'ETIMEDOUT'); assert.strictEqual(ret.error.errno, 'ETIMEDOUT');
const end = Date.now() - start; const end = Date.now() - start;
assert(end < SLEEP); assert(end < SLEEP);

View File

@ -69,9 +69,9 @@ const errMessage = /Invalid IV length/;
// But non-empty IVs should be rejected. // But non-empty IVs should be rejected.
for (let n = 1; n < 256; n += 1) { for (let n = 1; n < 256; n += 1) {
assert.throws( assert.throws(
() => crypto.createCipheriv('aes-128-ecb', Buffer.alloc(16), () => crypto.createCipheriv('aes-128-ecb', Buffer.alloc(16),
Buffer.alloc(n)), Buffer.alloc(n)),
errMessage); errMessage);
} }
// Correctly sized IV should be accepted in CBC mode. // Correctly sized IV should be accepted in CBC mode.
@ -81,16 +81,16 @@ crypto.createCipheriv('aes-128-cbc', Buffer.alloc(16), Buffer.alloc(16));
for (let n = 0; n < 256; n += 1) { for (let n = 0; n < 256; n += 1) {
if (n === 16) continue; if (n === 16) continue;
assert.throws( assert.throws(
() => crypto.createCipheriv('aes-128-cbc', Buffer.alloc(16), () => crypto.createCipheriv('aes-128-cbc', Buffer.alloc(16),
Buffer.alloc(n)), Buffer.alloc(n)),
errMessage); errMessage);
} }
// Zero-sized IV should be rejected in GCM mode. // Zero-sized IV should be rejected in GCM mode.
assert.throws( assert.throws(
() => crypto.createCipheriv('aes-128-gcm', Buffer.alloc(16), () => crypto.createCipheriv('aes-128-gcm', Buffer.alloc(16),
Buffer.alloc(0)), Buffer.alloc(0)),
errMessage); errMessage);
// But all other IV lengths should be accepted. // But all other IV lengths should be accepted.
for (let n = 1; n < 256; n += 1) { for (let n = 1; n < 256; n += 1) {

View File

@ -41,7 +41,7 @@ function testHelper(stream, args, expectedOutput, cmd, env) {
console.error( console.error(
`Spawned child [pid:${child.pid}] with cmd '${cmd}' expect %j with args '${ `Spawned child [pid:${child.pid}] with cmd '${cmd}' expect %j with args '${
args}' OPENSSL_CONF=%j`, expectedOutput, env.OPENSSL_CONF); args}' OPENSSL_CONF=%j`, expectedOutput, env.OPENSSL_CONF);
function childOk(child) { function childOk(child) {
console.error(`Child #${++num_children_ok} [pid:${child.pid}] OK.`); console.error(`Child #${++num_children_ok} [pid:${child.pid}] OK.`);

View File

@ -94,13 +94,13 @@ assert.throws(function() {
// Default UTF-8 encoding // Default UTF-8 encoding
const hutf8 = crypto.createHash('sha512').update('УТФ-8 text').digest('hex'); const hutf8 = crypto.createHash('sha512').update('УТФ-8 text').digest('hex');
assert.strictEqual( assert.strictEqual(
hutf8, hutf8,
'4b21bbd1a68e690a730ddcb5a8bc94ead9879ffe82580767ad7ec6fa8ba2dea6' + '4b21bbd1a68e690a730ddcb5a8bc94ead9879ffe82580767ad7ec6fa8ba2dea6' +
'43a821af66afa9a45b6a78c712fecf0e56dc7f43aef4bcfc8eb5b4d8dca6ea5b'); '43a821af66afa9a45b6a78c712fecf0e56dc7f43aef4bcfc8eb5b4d8dca6ea5b');
assert.notStrictEqual( assert.notStrictEqual(
hutf8, hutf8,
crypto.createHash('sha512').update('УТФ-8 text', 'latin1').digest('hex')); crypto.createHash('sha512').update('УТФ-8 text', 'latin1').digest('hex'));
const h3 = crypto.createHash('sha256'); const h3 = crypto.createHash('sha256');
h3.digest(); h3.digest();

View File

@ -267,8 +267,8 @@ const modSize = 1024;
const cmd = const cmd =
`"${common.opensslCli}" dgst -sha256 -verify "${pubfile}" -signature "${ `"${common.opensslCli}" dgst -sha256 -verify "${pubfile}" -signature "${
sigfile}" -sigopt rsa_padding_mode:pss -sigopt rsa_pss_saltlen:-2 "${ sigfile}" -sigopt rsa_padding_mode:pss -sigopt rsa_pss_saltlen:-2 "${
msgfile}"`; msgfile}"`;
exec(cmd, common.mustCall((err, stdout, stderr) => { exec(cmd, common.mustCall((err, stdout, stderr) => {
assert(stdout.includes('Verified OK')); assert(stdout.includes('Verified OK'));

View File

@ -46,8 +46,8 @@ server.bind(0, common.mustCall(() => {
assert.ifError(err); assert.ifError(err);
// Compare copies with ttl removed, c-ares fiddles with that value. // Compare copies with ttl removed, c-ares fiddles with that value.
assert.deepStrictEqual( assert.deepStrictEqual(
res.map((r) => Object.assign({}, r, { ttl: null })), res.map((r) => Object.assign({}, r, { ttl: null })),
answers.map((r) => Object.assign({}, r, { ttl: null }))); answers.map((r) => Object.assign({}, r, { ttl: null })));
server.close(); server.close();
})); }));
})); }));

View File

@ -34,7 +34,7 @@ domain.create().run(function() {
domain.create().run(function() { domain.create().run(function() {
domain.create().run(function() { domain.create().run(function() {
domain.create().on('error', function(e) { domain.create().on('error', function(e) {
// Don't need to do anything here // Don't need to do anything here
}).run(function() { }).run(function() {
throw new Error('died'); throw new Error('died');
}); });

View File

@ -185,7 +185,7 @@ if (process.argv[2] === 'child') {
const msgs = test.messagesReceived; const msgs = test.messagesReceived;
if (msgs === undefined || !msgs.includes(expectedMessage)) { if (msgs === undefined || !msgs.includes(expectedMessage)) {
assert.fail(`test ${test.fn.name} should have sent message: ${ assert.fail(`test ${test.fn.name} should have sent message: ${
expectedMessage} but didn't`); expectedMessage} but didn't`);
} }
}); });
@ -193,7 +193,7 @@ if (process.argv[2] === 'child') {
test.messagesReceived.forEach(function(receivedMessage) { test.messagesReceived.forEach(function(receivedMessage) {
if (!test.expectedMessages.includes(receivedMessage)) { if (!test.expectedMessages.includes(receivedMessage)) {
assert.fail(`test ${test.fn.name} should not have sent message: ${ assert.fail(`test ${test.fn.name} should not have sent message: ${
receivedMessage} but did`); receivedMessage} but did`);
} }
}); });
} }

View File

@ -81,7 +81,7 @@ d.on('error', function(er) {
break; break;
case case
"ENOENT: no such file or directory, open 'stream for nonexistent file'": "ENOENT: no such file or directory, open 'stream for nonexistent file'":
assert.strictEqual(typeof er.errno, 'number'); assert.strictEqual(typeof er.errno, 'number');
assert.strictEqual(er.code, 'ENOENT'); assert.strictEqual(er.code, 'ENOENT');
assert.strictEqual(er_path, 'stream for nonexistent file'); assert.strictEqual(er_path, 'stream for nonexistent file');

View File

@ -177,10 +177,10 @@ function run_test_3() {
const run_test_4 = common.mustCall(function() { const run_test_4 = common.mustCall(function() {
// Error: start must be >= zero // Error: start must be >= zero
assert.throws( assert.throws(
function() { function() {
fs.createWriteStream(filepath, { start: -5, flags: 'r+' }); fs.createWriteStream(filepath, { start: -5, flags: 'r+' });
}, },
/"start" must be/ /"start" must be/
); );
}); });

View File

@ -20,20 +20,20 @@ assert.throws(function() {
const enoentFile = path.join(common.tmpDir, 'non-existent-file'); const enoentFile = path.join(common.tmpDir, 'non-existent-file');
const expectedStatObject = new fs.Stats( const expectedStatObject = new fs.Stats(
0, // dev 0, // dev
0, // mode 0, // mode
0, // nlink 0, // nlink
0, // uid 0, // uid
0, // gid 0, // gid
0, // rdev 0, // rdev
common.isWindows ? undefined : 0, // blksize common.isWindows ? undefined : 0, // blksize
0, // ino 0, // ino
0, // size 0, // size
common.isWindows ? undefined : 0, // blocks common.isWindows ? undefined : 0, // blocks
Date.UTC(1970, 0, 1, 0, 0, 0), // atime Date.UTC(1970, 0, 1, 0, 0, 0), // atime
Date.UTC(1970, 0, 1, 0, 0, 0), // mtime Date.UTC(1970, 0, 1, 0, 0, 0), // mtime
Date.UTC(1970, 0, 1, 0, 0, 0), // ctime Date.UTC(1970, 0, 1, 0, 0, 0), // ctime
Date.UTC(1970, 0, 1, 0, 0, 0) // birthtime Date.UTC(1970, 0, 1, 0, 0, 0) // birthtime
); );
common.refreshTmpDir(); common.refreshTmpDir();

View File

@ -19,8 +19,8 @@ const strictEqual = require('assert').strictEqual;
strictEqual(cp._handle.hasRef(), strictEqual(cp._handle.hasRef(),
true, 'process_wrap: ref() ineffective'); true, 'process_wrap: ref() ineffective');
cp._handle.close(common.mustCall(() => cp._handle.close(common.mustCall(() =>
strictEqual(cp._handle.hasRef(), strictEqual(cp._handle.hasRef(),
false, 'process_wrap: not unrefed on close'))); false, 'process_wrap: not unrefed on close')));
} }
@ -40,8 +40,8 @@ const dgram = require('dgram');
strictEqual(sock4._handle.hasRef(), strictEqual(sock4._handle.hasRef(),
true, 'udp_wrap: ipv4: ref() ineffective'); true, 'udp_wrap: ipv4: ref() ineffective');
sock4._handle.close(common.mustCall(() => sock4._handle.close(common.mustCall(() =>
strictEqual(sock4._handle.hasRef(), strictEqual(sock4._handle.hasRef(),
false, 'udp_wrap: ipv4: not unrefed on close'))); false, 'udp_wrap: ipv4: not unrefed on close')));
} }
@ -59,8 +59,8 @@ const dgram = require('dgram');
strictEqual(sock6._handle.hasRef(), strictEqual(sock6._handle.hasRef(),
true, 'udp_wrap: ipv6: ref() ineffective'); true, 'udp_wrap: ipv6: ref() ineffective');
sock6._handle.close(common.mustCall(() => sock6._handle.close(common.mustCall(() =>
strictEqual(sock6._handle.hasRef(), strictEqual(sock6._handle.hasRef(),
false, 'udp_wrap: ipv6: not unrefed on close'))); false, 'udp_wrap: ipv6: not unrefed on close')));
} }
@ -79,8 +79,8 @@ const dgram = require('dgram');
strictEqual(handle.hasRef(), strictEqual(handle.hasRef(),
true, 'pipe_wrap: ref() ineffective'); true, 'pipe_wrap: ref() ineffective');
handle.close(common.mustCall(() => handle.close(common.mustCall(() =>
strictEqual(handle.hasRef(), strictEqual(handle.hasRef(),
false, 'pipe_wrap: not unrefed on close'))); false, 'pipe_wrap: not unrefed on close')));
} }
@ -105,8 +105,8 @@ const dgram = require('dgram');
strictEqual(server._unref, strictEqual(server._unref,
false, 'tcp_wrap: _unref not updated on ref()'); false, 'tcp_wrap: _unref not updated on ref()');
server._handle.close(common.mustCall(() => server._handle.close(common.mustCall(() =>
strictEqual(server._handle.hasRef(), strictEqual(server._handle.hasRef(),
false, 'tcp_wrap: not unrefed on close'))); false, 'tcp_wrap: not unrefed on close')));
} }
@ -122,8 +122,8 @@ const dgram = require('dgram');
strictEqual(timer._handle.hasRef(), strictEqual(timer._handle.hasRef(),
true, 'timer_wrap: ref() ineffective'); true, 'timer_wrap: ref() ineffective');
timer._handle.close(common.mustCall(() => timer._handle.close(common.mustCall(() =>
strictEqual(timer._handle.hasRef(), strictEqual(timer._handle.hasRef(),
false, 'timer_wrap: not unrefed on close'))); false, 'timer_wrap: not unrefed on close')));
} }

View File

@ -81,4 +81,4 @@ test1
console.error(e); console.error(e);
process.exit(1); process.exit(1);
} }
); );

View File

@ -38,9 +38,9 @@ const s = http.createServer(function(req, res) {
// This checks that after the headers have been sent, getHeader works // This checks that after the headers have been sent, getHeader works
// and does not throw an exception (Issue 752) // and does not throw an exception (Issue 752)
assert.doesNotThrow( assert.doesNotThrow(
function() { function() {
assert.strictEqual(plain, res.getHeader(contentType)); assert.strictEqual(plain, res.getHeader(contentType));
} }
); );
}); });

View File

@ -84,8 +84,8 @@ server.on('listening', function() {
outstanding_reqs--; outstanding_reqs--;
clearTimeout(tid); clearTimeout(tid);
assert.ok( assert.ok(
/0\r\nx-foo: bar\r\n\r\n$/.test(res_buffer), /0\r\nx-foo: bar\r\n\r\n$/.test(res_buffer),
'No trailer in HTTP/1.1 response.' 'No trailer in HTTP/1.1 response.'
); );
if (outstanding_reqs === 0) { if (outstanding_reqs === 0) {
server.close(); server.close();

View File

@ -54,7 +54,7 @@ const server = net.createServer(function(socket) {
assert.strictEqual( assert.strictEqual(
req.shouldKeepAlive, SHOULD_KEEP_ALIVE[responses], req.shouldKeepAlive, SHOULD_KEEP_ALIVE[responses],
`${SERVER_RESPONSES[responses]} should ${ `${SERVER_RESPONSES[responses]} should ${
SHOULD_KEEP_ALIVE[responses] ? '' : 'not '}Keep-Alive`); SHOULD_KEEP_ALIVE[responses] ? '' : 'not '}Keep-Alive`);
++responses; ++responses;
if (responses < SHOULD_KEEP_ALIVE.length) { if (responses < SHOULD_KEEP_ALIVE.length) {
makeRequest(); makeRequest();

View File

@ -57,9 +57,9 @@ const s = http.createServer(common.mustCall((req, res) => {
assert.throws(() => { assert.throws(() => {
res.writeHead(100, {}); res.writeHead(100, {});
}, common.expectsError({ }, common.expectsError({
code: 'ERR_HTTP_HEADERS_SENT', code: 'ERR_HTTP_HEADERS_SENT',
type: Error, type: Error,
message: 'Cannot render headers after they are sent to the client' message: 'Cannot render headers after they are sent to the client'
}) })
); );

View File

@ -143,9 +143,9 @@ function makeReq(path, port, error, host, ca) {
} }
const req = https.get(options); const req = https.get(options);
const server = port === server1.address().port ? server1 : const server = port === server1.address().port ? server1 :
port === server2.address().port ? server2 : port === server2.address().port ? server2 :
port === server3.address().port ? server3 : port === server3.address().port ? server3 :
null; null;
if (!server) throw new Error(`invalid port: ${port}`); if (!server) throw new Error(`invalid port: ${port}`);
server.expectCount++; server.expectCount++;

View File

@ -55,7 +55,7 @@ assert.strictEqual(readline.getStringWidth(0x20DD), 0);
// individually. // individually.
assert.strictEqual(readline.getStringWidth('👩‍👩‍👧‍👧'), 2); assert.strictEqual(readline.getStringWidth('👩‍👩‍👧‍👧'), 2);
assert.strictEqual( assert.strictEqual(
readline.getStringWidth('👩‍👩‍👧‍👧', { expandEmojiSequence: true }), 8); readline.getStringWidth('👩‍👩‍👧‍👧', { expandEmojiSequence: true }), 8);
// By default, unicode characters whose width is considered ambiguous will // By default, unicode characters whose width is considered ambiguous will
// be considered half-width. For these characters, getStringWidth will return // be considered half-width. For these characters, getStringWidth will return
@ -65,7 +65,7 @@ assert.strictEqual(
// as 2 columns. // as 2 columns.
assert.strictEqual(readline.getStringWidth('\u01d4'), 1); assert.strictEqual(readline.getStringWidth('\u01d4'), 1);
assert.strictEqual( assert.strictEqual(
readline.getStringWidth('\u01d4', { ambiguousAsFullWidth: true }), 2); readline.getStringWidth('\u01d4', { ambiguousAsFullWidth: true }), 2);
// Control chars and combining chars are zero // Control chars and combining chars are zero
assert.strictEqual(readline.getStringWidth('\u200E\n\u220A\u20D2'), 1); assert.strictEqual(readline.getStringWidth('\u200E\n\u220A\u20D2'), 1);

View File

@ -57,21 +57,21 @@ assert.throws(
); );
assert.deepStrictEqual( assert.deepStrictEqual(
buffer.transcode(Buffer.from('hi', 'ascii'), 'ascii', 'utf16le'), buffer.transcode(Buffer.from('hi', 'ascii'), 'ascii', 'utf16le'),
Buffer.from('hi', 'utf16le')); Buffer.from('hi', 'utf16le'));
assert.deepStrictEqual( assert.deepStrictEqual(
buffer.transcode(Buffer.from('hi', 'latin1'), 'latin1', 'utf16le'), buffer.transcode(Buffer.from('hi', 'latin1'), 'latin1', 'utf16le'),
Buffer.from('hi', 'utf16le')); Buffer.from('hi', 'utf16le'));
assert.deepStrictEqual( assert.deepStrictEqual(
buffer.transcode(Buffer.from('hä', 'latin1'), 'latin1', 'utf16le'), buffer.transcode(Buffer.from('hä', 'latin1'), 'latin1', 'utf16le'),
Buffer.from('hä', 'utf16le')); Buffer.from('hä', 'utf16le'));
// Test that Uint8Array arguments are okay. // Test that Uint8Array arguments are okay.
{ {
const uint8array = new Uint8Array([...Buffer.from('hä', 'latin1')]); const uint8array = new Uint8Array([...Buffer.from('hä', 'latin1')]);
assert.deepStrictEqual( assert.deepStrictEqual(
buffer.transcode(uint8array, 'latin1', 'utf16le'), buffer.transcode(uint8array, 'latin1', 'utf16le'),
Buffer.from('hä', 'utf16le')); Buffer.from('hä', 'utf16le'));
} }
{ {

View File

@ -233,5 +233,5 @@ assert.throws(
// Test ERR_TLS_CERT_ALTNAME_INVALID // Test ERR_TLS_CERT_ALTNAME_INVALID
assert.strictEqual( assert.strictEqual(
errors.message('ERR_TLS_CERT_ALTNAME_INVALID', ['altname']), errors.message('ERR_TLS_CERT_ALTNAME_INVALID', ['altname']),
'Hostname/IP does not match certificate\'s altnames: altname'); 'Hostname/IP does not match certificate\'s altnames: altname');

View File

@ -55,7 +55,7 @@ if (!common.hasIntl) {
} else { } else {
const erMsg = const erMsg =
`"Intl" object is present but v8_enable_i18n_support is ${ `"Intl" object is present but v8_enable_i18n_support is ${
enablei18n}. Is this test out of date?`; enablei18n}. Is this test out of date?`;
assert.strictEqual(enablei18n, 1, erMsg); assert.strictEqual(enablei18n, 1, erMsg);
// Construct a new date at the beginning of Unix time // Construct a new date at the beginning of Unix time

View File

@ -47,11 +47,11 @@ if (process.argv[2] === 'child') {
fs.mkdirSync(noPkgHomeDir); fs.mkdirSync(noPkgHomeDir);
env['HOME'] = env['USERPROFILE'] = noPkgHomeDir; env['HOME'] = env['USERPROFILE'] = noPkgHomeDir;
assert.throws( assert.throws(
() => { () => {
child_process.execFileSync(testExecPath, [ __filename, 'child' ], child_process.execFileSync(testExecPath, [ __filename, 'child' ],
{ encoding: 'utf8', env: env }); { encoding: 'utf8', env: env });
}, },
new RegExp(`Cannot find module '${pkgName}'`)); new RegExp(`Cannot find module '${pkgName}'`));
// Test module in $HOME/.node_modules. // Test module in $HOME/.node_modules.
const modHomeDir = path.join(testFixturesDir, 'home-pkg-in-node_modules'); const modHomeDir = path.join(testFixturesDir, 'home-pkg-in-node_modules');

View File

@ -8,23 +8,23 @@ if (!common.hasCrypto)
const assert = require('assert'); const assert = require('assert');
const os = require('os'); const os = require('os');
const childProcess = require('child_process'); const childProcess = require('child_process');
const result = childProcess.spawnSync(process.execPath, [ const result = childProcess.spawnSync(
'--use-bundled-ca', process.execPath,
'--use-openssl-ca', [ '--use-bundled-ca', '--use-openssl-ca', '-p', 'process.version' ],
'-p', 'process.version'], { encoding: 'utf8' }
{ encoding: 'utf8' }); );
assert.strictEqual(result.stderr, `${process.execPath assert.strictEqual(result.stderr, `${process.execPath
}: either --use-openssl-ca or --use-bundled-ca can be used, not both${os.EOL}` }: either --use-openssl-ca or --use-bundled-ca can be used, not both${os.EOL}`
); );
assert.strictEqual(result.status, 9); assert.strictEqual(result.status, 9);
const useBundledCA = childProcess.spawnSync(process.execPath, [ const useBundledCA = childProcess.spawnSync(process.execPath, [
'--use-bundled-ca', '--use-bundled-ca',
'-p', 'process.version']); '-p', 'process.version']);
assert.strictEqual(useBundledCA.status, 0); assert.strictEqual(useBundledCA.status, 0);
const useOpenSSLCA = childProcess.spawnSync(process.execPath, [ const useOpenSSLCA = childProcess.spawnSync(process.execPath, [
'--use-openssl-ca', '--use-openssl-ca',
'-p', 'process.version']); '-p', 'process.version']);
assert.strictEqual(useOpenSSLCA.status, 0); assert.strictEqual(useOpenSSLCA.status, 0);

View File

@ -115,25 +115,25 @@ if (!common.isSunOS) {
const interfaces = os.networkInterfaces(); const interfaces = os.networkInterfaces();
switch (platform) { switch (platform) {
case 'linux': case 'linux':
{ {
const filter = (e) => e.address === '127.0.0.1'; const filter = (e) => e.address === '127.0.0.1';
const actual = interfaces.lo.filter(filter); const actual = interfaces.lo.filter(filter);
const expected = [{ address: '127.0.0.1', netmask: '255.0.0.0', const expected = [{ address: '127.0.0.1', netmask: '255.0.0.0',
mac: '00:00:00:00:00:00', family: 'IPv4', mac: '00:00:00:00:00:00', family: 'IPv4',
internal: true }]; internal: true }];
assert.deepStrictEqual(actual, expected); assert.deepStrictEqual(actual, expected);
break; break;
} }
case 'win32': case 'win32':
{ {
const filter = (e) => e.address === '127.0.0.1'; const filter = (e) => e.address === '127.0.0.1';
const actual = interfaces['Loopback Pseudo-Interface 1'].filter(filter); const actual = interfaces['Loopback Pseudo-Interface 1'].filter(filter);
const expected = [{ address: '127.0.0.1', netmask: '255.0.0.0', const expected = [{ address: '127.0.0.1', netmask: '255.0.0.0',
mac: '00:00:00:00:00:00', family: 'IPv4', mac: '00:00:00:00:00:00', family: 'IPv4',
internal: true }]; internal: true }];
assert.deepStrictEqual(actual, expected); assert.deepStrictEqual(actual, expected);
break; break;
} }
} }
const EOL = os.EOL; const EOL = os.EOL;

View File

@ -287,51 +287,51 @@ joinTests.push([
path.win32.join, path.win32.join,
joinTests[0][1].slice(0).concat( joinTests[0][1].slice(0).concat(
[// arguments result [// arguments result
// UNC path expected // UNC path expected
[['//foo/bar'], '\\\\foo\\bar\\'], [['//foo/bar'], '\\\\foo\\bar\\'],
[['\\/foo/bar'], '\\\\foo\\bar\\'], [['\\/foo/bar'], '\\\\foo\\bar\\'],
[['\\\\foo/bar'], '\\\\foo\\bar\\'], [['\\\\foo/bar'], '\\\\foo\\bar\\'],
// UNC path expected - server and share separate // UNC path expected - server and share separate
[['//foo', 'bar'], '\\\\foo\\bar\\'], [['//foo', 'bar'], '\\\\foo\\bar\\'],
[['//foo/', 'bar'], '\\\\foo\\bar\\'], [['//foo/', 'bar'], '\\\\foo\\bar\\'],
[['//foo', '/bar'], '\\\\foo\\bar\\'], [['//foo', '/bar'], '\\\\foo\\bar\\'],
// UNC path expected - questionable // UNC path expected - questionable
[['//foo', '', 'bar'], '\\\\foo\\bar\\'], [['//foo', '', 'bar'], '\\\\foo\\bar\\'],
[['//foo/', '', 'bar'], '\\\\foo\\bar\\'], [['//foo/', '', 'bar'], '\\\\foo\\bar\\'],
[['//foo/', '', '/bar'], '\\\\foo\\bar\\'], [['//foo/', '', '/bar'], '\\\\foo\\bar\\'],
// UNC path expected - even more questionable // UNC path expected - even more questionable
[['', '//foo', 'bar'], '\\\\foo\\bar\\'], [['', '//foo', 'bar'], '\\\\foo\\bar\\'],
[['', '//foo/', 'bar'], '\\\\foo\\bar\\'], [['', '//foo/', 'bar'], '\\\\foo\\bar\\'],
[['', '//foo/', '/bar'], '\\\\foo\\bar\\'], [['', '//foo/', '/bar'], '\\\\foo\\bar\\'],
// No UNC path expected (no double slash in first component) // No UNC path expected (no double slash in first component)
[['\\', 'foo/bar'], '\\foo\\bar'], [['\\', 'foo/bar'], '\\foo\\bar'],
[['\\', '/foo/bar'], '\\foo\\bar'], [['\\', '/foo/bar'], '\\foo\\bar'],
[['', '/', '/foo/bar'], '\\foo\\bar'], [['', '/', '/foo/bar'], '\\foo\\bar'],
// No UNC path expected (no non-slashes in first component - // No UNC path expected (no non-slashes in first component -
// questionable) // questionable)
[['//', 'foo/bar'], '\\foo\\bar'], [['//', 'foo/bar'], '\\foo\\bar'],
[['//', '/foo/bar'], '\\foo\\bar'], [['//', '/foo/bar'], '\\foo\\bar'],
[['\\\\', '/', '/foo/bar'], '\\foo\\bar'], [['\\\\', '/', '/foo/bar'], '\\foo\\bar'],
[['//'], '/'], [['//'], '/'],
// No UNC path expected (share name missing - questionable). // No UNC path expected (share name missing - questionable).
[['//foo'], '\\foo'], [['//foo'], '\\foo'],
[['//foo/'], '\\foo\\'], [['//foo/'], '\\foo\\'],
[['//foo', '/'], '\\foo\\'], [['//foo', '/'], '\\foo\\'],
[['//foo', '', '/'], '\\foo\\'], [['//foo', '', '/'], '\\foo\\'],
// No UNC path expected (too many leading slashes - questionable) // No UNC path expected (too many leading slashes - questionable)
[['///foo/bar'], '\\foo\\bar'], [['///foo/bar'], '\\foo\\bar'],
[['////foo', 'bar'], '\\foo\\bar'], [['////foo', 'bar'], '\\foo\\bar'],
[['\\\\\\/foo/bar'], '\\foo\\bar'], [['\\\\\\/foo/bar'], '\\foo\\bar'],
// Drive-relative vs drive-absolute paths. This merely describes the // Drive-relative vs drive-absolute paths. This merely describes the
// status quo, rather than being obviously right // status quo, rather than being obviously right
[['c:'], 'c:.'], [['c:'], 'c:.'],
[['c:.'], 'c:.'], [['c:.'], 'c:.'],
[['c:', ''], 'c:.'], [['c:', ''], 'c:.'],
[['', 'c:'], 'c:.'], [['', 'c:'], 'c:.'],
[['c:.', '/'], 'c:.\\'], [['c:.', '/'], 'c:.\\'],
[['c:.', 'file'], 'c:file'], [['c:.', 'file'], 'c:file'],
[['c:', '/'], 'c:\\'], [['c:', '/'], 'c:\\'],
[['c:', 'file'], 'c:\\file'] [['c:', 'file'], 'c:\\file']
] ]
) )
]); ]);
@ -461,7 +461,7 @@ resolveTests.forEach((test) => {
const expected = test[1]; const expected = test[1];
const message = const message =
`path.${os}.resolve(${test[0].map(JSON.stringify).join(',')})\n expect=${ `path.${os}.resolve(${test[0].map(JSON.stringify).join(',')})\n expect=${
JSON.stringify(expected)}\n actual=${JSON.stringify(actual)}`; JSON.stringify(expected)}\n actual=${JSON.stringify(actual)}`;
if (actual !== expected && actualAlt !== expected) if (actual !== expected && actualAlt !== expected)
failures.push(`\n${message}`); failures.push(`\n${message}`);
}); });

View File

@ -104,7 +104,7 @@ replProc.on('close', function(code) {
// also test that duplicated preload only gets loaded once // also test that duplicated preload only gets loaded once
childProcess.exec( childProcess.exec(
`"${nodeBinary}" ${preloadOption([fixtureA])}-e "console.log('hello');" ${ `"${nodeBinary}" ${preloadOption([fixtureA])}-e "console.log('hello');" ${
preloadOption([fixtureA, fixtureB])}`, preloadOption([fixtureA, fixtureB])}`,
function(err, stdout, stderr) { function(err, stdout, stderr) {
assert.ifError(err); assert.ifError(err);
assert.strictEqual(stdout, 'A\nB\nhello\n'); assert.strictEqual(stdout, 'A\nB\nhello\n');
@ -125,7 +125,7 @@ interactive.stdin.write('process.exit()\n');
childProcess.exec( childProcess.exec(
`"${nodeBinary}" --require "${fixture('cluster-preload.js')}" "${ `"${nodeBinary}" --require "${fixture('cluster-preload.js')}" "${
fixture('cluster-preload-test.js')}"`, fixture('cluster-preload-test.js')}"`,
function(err, stdout, stderr) { function(err, stdout, stderr) {
assert.ifError(err); assert.ifError(err);
assert.ok(/worker terminated with code 43/.test(stdout)); assert.ok(/worker terminated with code 43/.test(stdout));

View File

@ -6,16 +6,16 @@ assert.strictEqual(process.assert(1, 'error'), undefined);
assert.throws(() => { assert.throws(() => {
process.assert(undefined, 'errorMessage'); process.assert(undefined, 'errorMessage');
}, common.expectsError({ }, common.expectsError({
code: 'ERR_ASSERTION', code: 'ERR_ASSERTION',
type: Error, type: Error,
message: 'errorMessage' message: 'errorMessage'
}) })
); );
assert.throws(() => { assert.throws(() => {
process.assert(false); process.assert(false);
}, common.expectsError({ }, common.expectsError({
code: 'ERR_ASSERTION', code: 'ERR_ASSERTION',
type: Error, type: Error,
message: 'assertion error' message: 'assertion error'
}) })
); );

View File

@ -328,13 +328,13 @@ check(qs.parse('a', null, []), { '': 'a' });
// Test limiting // Test limiting
assert.strictEqual( assert.strictEqual(
Object.keys(qs.parse('a=1&b=1&c=1', null, null, { maxKeys: 1 })).length, Object.keys(qs.parse('a=1&b=1&c=1', null, null, { maxKeys: 1 })).length,
1); 1);
// Test limiting with a case that starts from `&` // Test limiting with a case that starts from `&`
assert.strictEqual( assert.strictEqual(
Object.keys(qs.parse('&a', null, null, { maxKeys: 1 })).length, Object.keys(qs.parse('&a', null, null, { maxKeys: 1 })).length,
0); 0);
// Test removing limit // Test removing limit
{ {
@ -356,7 +356,7 @@ assert.strictEqual(
{ {
const b = qs.unescapeBuffer('%d3%f2Ug%1f6v%24%5e%98%cb' + const b = qs.unescapeBuffer('%d3%f2Ug%1f6v%24%5e%98%cb' +
'%0d%ac%a2%2f%9d%eb%d8%a2%e6'); '%0d%ac%a2%2f%9d%eb%d8%a2%e6');
// <Buffer d3 f2 55 67 1f 36 76 24 5e 98 cb 0d ac a2 2f 9d eb d8 a2 e6> // <Buffer d3 f2 55 67 1f 36 76 24 5e 98 cb 0d ac a2 2f 9d eb d8 a2 e6>
assert.strictEqual(0xd3, b[0]); assert.strictEqual(0xd3, b[0]);
assert.strictEqual(0xf2, b[1]); assert.strictEqual(0xf2, b[1]);
assert.strictEqual(0x55, b[2]); assert.strictEqual(0x55, b[2]);
@ -411,7 +411,7 @@ check(qs.parse('%\u0100=%\u0101'), { '%Ā': '%ā' });
} }
check(qs.parse('a=a', null, null, { decodeURIComponent: errDecode }), check(qs.parse('a=a', null, null, { decodeURIComponent: errDecode }),
{ a: 'a' }); { a: 'a' });
} }
// Test custom encode // Test custom encode

View File

@ -32,7 +32,7 @@ function testStrictMode() {
cli.input.emit('data', 'x = 3\n'); cli.input.emit('data', 'x = 3\n');
assert.ok(/ReferenceError: x is not defined/.test( assert.ok(/ReferenceError: x is not defined/.test(
cli.output.accumulator.join(''))); cli.output.accumulator.join('')));
cli.output.accumulator.length = 0; cli.output.accumulator.length = 0;
cli.input.emit('data', 'let y = 3\n'); cli.input.emit('data', 'let y = 3\n');

View File

@ -7,7 +7,7 @@ const zlib = require('zlib');
// just use builtin stream inherited from Duplex // just use builtin stream inherited from Duplex
const putIn = zlib.createGzip(); const putIn = zlib.createGzip();
const testMe = repl.start('', putIn, function(cmd, context, filename, const testMe = repl.start('', putIn, function(cmd, context, filename,
callback) { callback) {
callback(null, cmd); callback(null, cmd);
}); });

View File

@ -80,7 +80,7 @@ function runRepl(useGlobal, testFunc, cb) {
}; };
repl.createInternalRepl( repl.createInternalRepl(
process.env, process.env,
opts, opts,
testFunc(useGlobal, cb, opts.output)); testFunc(useGlobal, cb, opts.output));
} }

View File

@ -85,9 +85,9 @@ function error_test() {
read_buffer += data.toString('ascii', 0, data.length); read_buffer += data.toString('ascii', 0, data.length);
console.error( console.error(
`Unix data: ${JSON.stringify(read_buffer)}, expecting ${ `Unix data: ${JSON.stringify(read_buffer)}, expecting ${
client_unix.expect.exec ? client_unix.expect.exec ?
client_unix.expect : client_unix.expect :
JSON.stringify(client_unix.expect)}`); JSON.stringify(client_unix.expect)}`);
if (read_buffer.includes(prompt_unix)) { if (read_buffer.includes(prompt_unix)) {
// if it's an exact match, then don't do the regexp // if it's an exact match, then don't do the regexp
@ -268,7 +268,7 @@ function error_test() {
// do not fail when a String is created with line continuation // do not fail when a String is created with line continuation
{ client: client_unix, send: '\'the\\\nfourth\\\neye\'', { client: client_unix, send: '\'the\\\nfourth\\\neye\'',
expect: `${prompt_multiline}${prompt_multiline}'thefourtheye'\n${ expect: `${prompt_multiline}${prompt_multiline}'thefourtheye'\n${
prompt_unix}` }, prompt_unix}` },
// Don't fail when a partial String is created and line continuation is used // Don't fail when a partial String is created and line continuation is used
// with whitespace characters at the end of the string. We are to ignore it. // with whitespace characters at the end of the string. We are to ignore it.
// This test is to make sure that we properly remove the whitespace // This test is to make sure that we properly remove the whitespace
@ -278,11 +278,11 @@ function error_test() {
// multiline strings preserve whitespace characters in them // multiline strings preserve whitespace characters in them
{ client: client_unix, send: '\'the \\\n fourth\t\t\\\n eye \'', { client: client_unix, send: '\'the \\\n fourth\t\t\\\n eye \'',
expect: `${prompt_multiline}${ expect: `${prompt_multiline}${
prompt_multiline}'the fourth\\t\\t eye '\n${prompt_unix}` }, prompt_multiline}'the fourth\\t\\t eye '\n${prompt_unix}` },
// more than one multiline strings also should preserve whitespace chars // more than one multiline strings also should preserve whitespace chars
{ client: client_unix, send: '\'the \\\n fourth\' + \'\t\t\\\n eye \'', { client: client_unix, send: '\'the \\\n fourth\' + \'\t\t\\\n eye \'',
expect: `${prompt_multiline}${ expect: `${prompt_multiline}${
prompt_multiline}'the fourth\\t\\t eye '\n${prompt_unix}` }, prompt_multiline}'the fourth\\t\\t eye '\n${prompt_unix}` },
// using REPL commands within a string literal should still work // using REPL commands within a string literal should still work
{ client: client_unix, send: '\'\\\n.break', { client: client_unix, send: '\'\\\n.break',
expect: prompt_unix }, expect: prompt_unix },
@ -295,7 +295,7 @@ function error_test() {
// empty lines in the string literals should not affect the string // empty lines in the string literals should not affect the string
{ client: client_unix, send: '\'the\\\n\\\nfourtheye\'\n', { client: client_unix, send: '\'the\\\n\\\nfourtheye\'\n',
expect: `${prompt_multiline}${ expect: `${prompt_multiline}${
prompt_multiline}'thefourtheye'\n${prompt_unix}` }, prompt_multiline}'thefourtheye'\n${prompt_unix}` },
// Regression test for https://github.com/nodejs/node/issues/597 // Regression test for https://github.com/nodejs/node/issues/597
{ client: client_unix, { client: client_unix,
send: '/(.)(.)(.)(.)(.)(.)(.)(.)(.)/.test(\'123456789\')\n', send: '/(.)(.)(.)(.)(.)(.)(.)(.)(.)/.test(\'123456789\')\n',
@ -309,24 +309,24 @@ function error_test() {
// regression tests for https://github.com/nodejs/node/issues/2749 // regression tests for https://github.com/nodejs/node/issues/2749
{ client: client_unix, send: 'function x() {\nreturn \'\\n\';\n }', { client: client_unix, send: 'function x() {\nreturn \'\\n\';\n }',
expect: `${prompt_multiline}${prompt_multiline}undefined\n${ expect: `${prompt_multiline}${prompt_multiline}undefined\n${
prompt_unix}` }, prompt_unix}` },
{ client: client_unix, send: 'function x() {\nreturn \'\\\\\';\n }', { client: client_unix, send: 'function x() {\nreturn \'\\\\\';\n }',
expect: `${prompt_multiline}${prompt_multiline}undefined\n${ expect: `${prompt_multiline}${prompt_multiline}undefined\n${
prompt_unix}` }, prompt_unix}` },
// regression tests for https://github.com/nodejs/node/issues/3421 // regression tests for https://github.com/nodejs/node/issues/3421
{ client: client_unix, send: 'function x() {\n//\'\n }', { client: client_unix, send: 'function x() {\n//\'\n }',
expect: `${prompt_multiline}${prompt_multiline}undefined\n${ expect: `${prompt_multiline}${prompt_multiline}undefined\n${
prompt_unix}` }, prompt_unix}` },
{ client: client_unix, send: 'function x() {\n//"\n }', { client: client_unix, send: 'function x() {\n//"\n }',
expect: `${prompt_multiline}${prompt_multiline}undefined\n${ expect: `${prompt_multiline}${prompt_multiline}undefined\n${
prompt_unix}` }, prompt_unix}` },
{ client: client_unix, send: 'function x() {//\'\n }', { client: client_unix, send: 'function x() {//\'\n }',
expect: `${prompt_multiline}undefined\n${prompt_unix}` }, expect: `${prompt_multiline}undefined\n${prompt_unix}` },
{ client: client_unix, send: 'function x() {//"\n }', { client: client_unix, send: 'function x() {//"\n }',
expect: `${prompt_multiline}undefined\n${prompt_unix}` }, expect: `${prompt_multiline}undefined\n${prompt_unix}` },
{ client: client_unix, send: 'function x() {\nvar i = "\'";\n }', { client: client_unix, send: 'function x() {\nvar i = "\'";\n }',
expect: `${prompt_multiline}${prompt_multiline}undefined\n${ expect: `${prompt_multiline}${prompt_multiline}undefined\n${
prompt_unix}` }, prompt_unix}` },
{ client: client_unix, send: 'function x(/*optional*/) {}', { client: client_unix, send: 'function x(/*optional*/) {}',
expect: `undefined\n${prompt_unix}` }, expect: `undefined\n${prompt_unix}` },
{ client: client_unix, send: 'function x(/* // 5 */) {}', { client: client_unix, send: 'function x(/* // 5 */) {}',
@ -454,7 +454,7 @@ function tcp_test() {
client_tcp.on('data', function(data) { client_tcp.on('data', function(data) {
read_buffer += data.toString('ascii', 0, data.length); read_buffer += data.toString('ascii', 0, data.length);
console.error(`TCP data: ${JSON.stringify(read_buffer)}, expecting ${ console.error(`TCP data: ${JSON.stringify(read_buffer)}, expecting ${
JSON.stringify(client_tcp.expect)}`); JSON.stringify(client_tcp.expect)}`);
if (read_buffer.includes(prompt_tcp)) { if (read_buffer.includes(prompt_tcp)) {
assert.strictEqual(client_tcp.expect, read_buffer); assert.strictEqual(client_tcp.expect, read_buffer);
console.error('match'); console.error('match');
@ -524,7 +524,7 @@ function unix_test() {
client_unix.on('data', function(data) { client_unix.on('data', function(data) {
read_buffer += data.toString('ascii', 0, data.length); read_buffer += data.toString('ascii', 0, data.length);
console.error(`Unix data: ${JSON.stringify(read_buffer)}, expecting ${ console.error(`Unix data: ${JSON.stringify(read_buffer)}, expecting ${
JSON.stringify(client_unix.expect)}`); JSON.stringify(client_unix.expect)}`);
if (read_buffer.includes(prompt_unix)) { if (read_buffer.includes(prompt_unix)) {
assert.strictEqual(client_unix.expect, read_buffer); assert.strictEqual(client_unix.expect, read_buffer);
console.error('match'); console.error('match');

View File

@ -4,7 +4,7 @@ const common = require('../common');
const fixturesRequire = require(`${common.fixturesDir}/require-bin/bin/req.js`); const fixturesRequire = require(`${common.fixturesDir}/require-bin/bin/req.js`);
assert.strictEqual( assert.strictEqual(
fixturesRequire, fixturesRequire,
'', '',
'test-require-extensions-main failed to import fixture requirements' 'test-require-extensions-main failed to import fixture requirements'
); );

View File

@ -26,14 +26,14 @@ const assert = require('assert');
const path = require('path'); const path = require('path');
assert.strictEqual( assert.strictEqual(
path.join(__dirname, '../fixtures/a.js').toLowerCase(), path.join(__dirname, '../fixtures/a.js').toLowerCase(),
require.resolve('../fixtures/a').toLowerCase()); require.resolve('../fixtures/a').toLowerCase());
assert.strictEqual( assert.strictEqual(
path.join(fixturesDir, 'a.js').toLowerCase(), path.join(fixturesDir, 'a.js').toLowerCase(),
require.resolve(path.join(fixturesDir, 'a')).toLowerCase()); require.resolve(path.join(fixturesDir, 'a')).toLowerCase());
assert.strictEqual( assert.strictEqual(
path.join(fixturesDir, 'nested-index', 'one', 'index.js').toLowerCase(), path.join(fixturesDir, 'nested-index', 'one', 'index.js').toLowerCase(),
require.resolve('../fixtures/nested-index/one').toLowerCase()); require.resolve('../fixtures/nested-index/one').toLowerCase());
assert.strictEqual('path', require.resolve('path')); assert.strictEqual('path', require.resolve('path'));
console.log('ok'); console.log('ok');

View File

@ -26,8 +26,8 @@ if (common.isWindows)
// To pass this test on alpine, since Busybox `ps` does not // To pass this test on alpine, since Busybox `ps` does not
// support `-p` switch, use `ps -o` and `grep` instead. // support `-p` switch, use `ps -o` and `grep` instead.
const cmd = common.isLinux ? const cmd = common.isLinux ?
`ps -o pid,args | grep '${process.pid} ${title}' | grep -v grep` : `ps -o pid,args | grep '${process.pid} ${title}' | grep -v grep` :
`ps -p ${process.pid} -o args=`; `ps -p ${process.pid} -o args=`;
exec(cmd, common.mustCall((error, stdout, stderr) => { exec(cmd, common.mustCall((error, stdout, stderr) => {
assert.ifError(error); assert.ifError(error);

View File

@ -5,8 +5,10 @@ const common = require('../common');
const assert = require('assert'); const assert = require('assert');
const child_process = require('child_process'); const child_process = require('child_process');
const path = require('path'); const path = require('path');
const cp = child_process.spawn(process.execPath, const cp = child_process.spawn(
[path.resolve(__dirname, 'test-stdin-pause-resume.js')]); process.execPath,
[path.resolve(__dirname, 'test-stdin-pause-resume.js')]
);
cp.on('exit', common.mustCall((code) => { cp.on('exit', common.mustCall((code) => {
assert.strictEqual(code, 0); assert.strictEqual(code, 0);

View File

@ -14,7 +14,7 @@ common.refreshTmpDir();
function test(size, useBuffer, cb) { function test(size, useBuffer, cb) {
const cmd = `"${process.argv[0]}" "${ const cmd = `"${process.argv[0]}" "${
useBuffer ? scriptBuffer : scriptString}" ${size} > "${tmpFile}"`; useBuffer ? scriptBuffer : scriptString}" ${size} > "${tmpFile}"`;
try { try {
fs.unlinkSync(tmpFile); fs.unlinkSync(tmpFile);

View File

@ -86,7 +86,7 @@ function test(decode, uncork, multi, next) {
return { return {
encoding: chunk.encoding, encoding: chunk.encoding,
chunk: Buffer.isBuffer(chunk.chunk) ? chunk: Buffer.isBuffer(chunk.chunk) ?
Array.prototype.slice.call(chunk.chunk) : chunk.chunk Array.prototype.slice.call(chunk.chunk) : chunk.chunk
}; };
}); });
cb(); cb();

View File

@ -28,7 +28,7 @@ assert.throws(() => tls.createServer({ handshakeTimeout: 'abcd' }),
type: TypeError, type: TypeError,
message: 'The "timeout" argument must be of type number' message: 'The "timeout" argument must be of type number'
}) })
); );
assert.throws(() => tls.createServer({ sessionTimeout: 'abcd' }), assert.throws(() => tls.createServer({ sessionTimeout: 'abcd' }),
/TypeError: Session timeout must be a 32-bit integer/); /TypeError: Session timeout must be a 32-bit integer/);

View File

@ -34,31 +34,31 @@ const testCases =
key: 'agent2-key', key: 'agent2-key',
cert: 'agent2-cert', cert: 'agent2-cert',
servers: [ servers: [
{ ok: true, key: 'agent1-key', cert: 'agent1-cert' }, { ok: true, key: 'agent1-key', cert: 'agent1-cert' },
{ ok: false, key: 'agent2-key', cert: 'agent2-cert' }, { ok: false, key: 'agent2-key', cert: 'agent2-cert' },
{ ok: false, key: 'agent3-key', cert: 'agent3-cert' } { ok: false, key: 'agent3-key', cert: 'agent3-cert' }
]
},
{ ca: [],
key: 'agent2-key',
cert: 'agent2-cert',
servers: [
{ ok: false, key: 'agent1-key', cert: 'agent1-cert' },
{ ok: false, key: 'agent2-key', cert: 'agent2-cert' },
{ ok: false, key: 'agent3-key', cert: 'agent3-cert' }
] ]
}, },
{ ca: [], { ca: ['ca1-cert', 'ca2-cert'],
key: 'agent2-key', key: 'agent2-key',
cert: 'agent2-cert', cert: 'agent2-cert',
servers: [ servers: [
{ ok: false, key: 'agent1-key', cert: 'agent1-cert' }, { ok: true, key: 'agent1-key', cert: 'agent1-cert' },
{ ok: false, key: 'agent2-key', cert: 'agent2-cert' }, { ok: false, key: 'agent2-key', cert: 'agent2-cert' },
{ ok: false, key: 'agent3-key', cert: 'agent3-cert' } { ok: true, key: 'agent3-key', cert: 'agent3-cert' }
] ]
}, }
{ ca: ['ca1-cert', 'ca2-cert'],
key: 'agent2-key',
cert: 'agent2-cert',
servers: [
{ ok: true, key: 'agent1-key', cert: 'agent1-cert' },
{ ok: false, key: 'agent2-key', cert: 'agent2-cert' },
{ ok: true, key: 'agent3-key', cert: 'agent3-cert' }
]
}
]; ];
function filenamePEM(n) { function filenamePEM(n) {

View File

@ -43,7 +43,7 @@ const server = tls.createServer(options, common.mustNotCall());
server.listen(0, '127.0.0.1', common.mustCall(function() { server.listen(0, '127.0.0.1', common.mustCall(function() {
let cmd = `"${common.opensslCli}" s_client -cipher ${ let cmd = `"${common.opensslCli}" s_client -cipher ${
options.ciphers} -connect 127.0.0.1:${this.address().port}`; options.ciphers} -connect 127.0.0.1:${this.address().port}`;
// for the performance and stability issue in s_client on Windows // for the performance and stability issue in s_client on Windows
if (common.isWindows) if (common.isWindows)

View File

@ -49,7 +49,7 @@ const server = tls.createServer(options, common.mustCall(function(conn) {
server.listen(0, '127.0.0.1', common.mustCall(function() { server.listen(0, '127.0.0.1', common.mustCall(function() {
let cmd = `"${common.opensslCli}" s_client -cipher ${ let cmd = `"${common.opensslCli}" s_client -cipher ${
options.ciphers} -connect 127.0.0.1:${this.address().port}`; options.ciphers} -connect 127.0.0.1:${this.address().port}`;
// for the performance and stability issue in s_client on Windows // for the performance and stability issue in s_client on Windows
if (common.isWindows) if (common.isWindows)

View File

@ -93,7 +93,7 @@ function test(testOptions, cb) {
port: this.address().port, port: this.address().port,
requestOCSP: testOptions.ocsp !== false, requestOCSP: testOptions.ocsp !== false,
secureOptions: testOptions.ocsp === false ? secureOptions: testOptions.ocsp === false ?
SSL_OP_NO_TICKET : 0, SSL_OP_NO_TICKET : 0,
rejectUnauthorized: false rejectUnauthorized: false
}, function() { }, function() {
clientSecure++; clientSecure++;

View File

@ -11,7 +11,7 @@ const fs = require('fs');
const path = require('path'); const path = require('path');
const pfx = fs.readFileSync( const pfx = fs.readFileSync(
path.join(common.fixturesDir, 'keys', 'agent1-pfx.pem')); path.join(common.fixturesDir, 'keys', 'agent1-pfx.pem'));
const server = tls.createServer({ const server = tls.createServer({
pfx: pfx, pfx: pfx,

View File

@ -52,80 +52,80 @@ const testCases =
CAs: ['ca1-cert'], CAs: ['ca1-cert'],
clients: clients:
[{ name: 'agent1', shouldReject: false, shouldAuth: false }, [{ name: 'agent1', shouldReject: false, shouldAuth: false },
{ name: 'agent2', shouldReject: false, shouldAuth: false }, { name: 'agent2', shouldReject: false, shouldAuth: false },
{ name: 'agent3', shouldReject: false, shouldAuth: false }, { name: 'agent3', shouldReject: false, shouldAuth: false },
{ name: 'nocert', shouldReject: false, shouldAuth: false } { name: 'nocert', shouldReject: false, shouldAuth: false }
] ]
}, },
{ title: 'Allow both authed and unauthed connections with CA1', { title: 'Allow both authed and unauthed connections with CA1',
requestCert: true, requestCert: true,
rejectUnauthorized: false, rejectUnauthorized: false,
renegotiate: false, renegotiate: false,
CAs: ['ca1-cert'], CAs: ['ca1-cert'],
clients: clients:
[{ name: 'agent1', shouldReject: false, shouldAuth: true }, [{ name: 'agent1', shouldReject: false, shouldAuth: true },
{ name: 'agent2', shouldReject: false, shouldAuth: false }, { name: 'agent2', shouldReject: false, shouldAuth: false },
{ name: 'agent3', shouldReject: false, shouldAuth: false }, { name: 'agent3', shouldReject: false, shouldAuth: false },
{ name: 'nocert', shouldReject: false, shouldAuth: false } { name: 'nocert', shouldReject: false, shouldAuth: false }
] ]
}, },
{ title: 'Do not request certs at connection. Do that later', { title: 'Do not request certs at connection. Do that later',
requestCert: false, requestCert: false,
rejectUnauthorized: false, rejectUnauthorized: false,
renegotiate: true, renegotiate: true,
CAs: ['ca1-cert'], CAs: ['ca1-cert'],
clients: clients:
[{ name: 'agent1', shouldReject: false, shouldAuth: true }, [{ name: 'agent1', shouldReject: false, shouldAuth: true },
{ name: 'agent2', shouldReject: false, shouldAuth: false }, { name: 'agent2', shouldReject: false, shouldAuth: false },
{ name: 'agent3', shouldReject: false, shouldAuth: false }, { name: 'agent3', shouldReject: false, shouldAuth: false },
{ name: 'nocert', shouldReject: false, shouldAuth: false } { name: 'nocert', shouldReject: false, shouldAuth: false }
] ]
}, },
{ title: 'Allow only authed connections with CA1', { title: 'Allow only authed connections with CA1',
requestCert: true, requestCert: true,
rejectUnauthorized: true, rejectUnauthorized: true,
renegotiate: false, renegotiate: false,
CAs: ['ca1-cert'], CAs: ['ca1-cert'],
clients: clients:
[{ name: 'agent1', shouldReject: false, shouldAuth: true }, [{ name: 'agent1', shouldReject: false, shouldAuth: true },
{ name: 'agent2', shouldReject: true }, { name: 'agent2', shouldReject: true },
{ name: 'agent3', shouldReject: true }, { name: 'agent3', shouldReject: true },
{ name: 'nocert', shouldReject: true } { name: 'nocert', shouldReject: true }
] ]
}, },
{ title: 'Allow only authed connections with CA1 and CA2', { title: 'Allow only authed connections with CA1 and CA2',
requestCert: true, requestCert: true,
rejectUnauthorized: true, rejectUnauthorized: true,
renegotiate: false, renegotiate: false,
CAs: ['ca1-cert', 'ca2-cert'], CAs: ['ca1-cert', 'ca2-cert'],
clients: clients:
[{ name: 'agent1', shouldReject: false, shouldAuth: true }, [{ name: 'agent1', shouldReject: false, shouldAuth: true },
{ name: 'agent2', shouldReject: true }, { name: 'agent2', shouldReject: true },
{ name: 'agent3', shouldReject: false, shouldAuth: true }, { name: 'agent3', shouldReject: false, shouldAuth: true },
{ name: 'nocert', shouldReject: true } { name: 'nocert', shouldReject: true }
] ]
}, },
{ title: 'Allow only certs signed by CA2 but not in the CRL', { title: 'Allow only certs signed by CA2 but not in the CRL',
requestCert: true, requestCert: true,
rejectUnauthorized: true, rejectUnauthorized: true,
renegotiate: false, renegotiate: false,
CAs: ['ca2-cert'], CAs: ['ca2-cert'],
crl: 'ca2-crl', crl: 'ca2-crl',
clients: [ clients: [
{ name: 'agent1', shouldReject: true, shouldAuth: false }, { name: 'agent1', shouldReject: true, shouldAuth: false },
{ name: 'agent2', shouldReject: true, shouldAuth: false }, { name: 'agent2', shouldReject: true, shouldAuth: false },
{ name: 'agent3', shouldReject: false, shouldAuth: true }, { name: 'agent3', shouldReject: false, shouldAuth: true },
// Agent4 has a cert in the CRL. // Agent4 has a cert in the CRL.
{ name: 'agent4', shouldReject: true, shouldAuth: false }, { name: 'agent4', shouldReject: true, shouldAuth: false },
{ name: 'nocert', shouldReject: true } { name: 'nocert', shouldReject: true }
] ]
} }
]; ];
@ -247,7 +247,7 @@ function runClient(prefix, port, options, cb) {
assert.strictEqual( assert.strictEqual(
options.shouldAuth, authed, options.shouldAuth, authed,
`${prefix}${options.name} authed is ${authed} but should have been ${ `${prefix}${options.name} authed is ${authed} but should have been ${
options.shouldAuth}`); options.shouldAuth}`);
} }
cb(); cb();
@ -313,7 +313,7 @@ function runTest(port, testIndex) {
if (c.authorized) { if (c.authorized) {
console.error(`${prefix}- authed connection: ${ console.error(`${prefix}- authed connection: ${
c.getPeerCertificate().subject.CN}`); c.getPeerCertificate().subject.CN}`);
c.write('\n_authed\n'); c.write('\n_authed\n');
} else { } else {
console.error(`${prefix}- unauthed connection: %s`, c.authorizationError); console.error(`${prefix}- unauthed connection: %s`, c.authorizationError);

View File

@ -52,7 +52,7 @@ const server = tls.createServer(options, common.mustCall(function(conn) {
server.listen(0, '127.0.0.1', function() { server.listen(0, '127.0.0.1', function() {
let cmd = `"${common.opensslCli}" s_client -cipher ${ let cmd = `"${common.opensslCli}" s_client -cipher ${
options.ciphers} -connect 127.0.0.1:${this.address().port}`; options.ciphers} -connect 127.0.0.1:${this.address().port}`;
// for the performance and stability issue in s_client on Windows // for the performance and stability issue in s_client on Windows
if (common.isWindows) if (common.isWindows)

View File

@ -141,7 +141,7 @@ function startTest() {
options.port = server.address().port; options.port = server.address().port;
const client = tls.connect(options, function() { const client = tls.connect(options, function() {
clientResults.push( clientResults.push(
client.authorizationError && client.authorizationError &&
(client.authorizationError === 'ERR_TLS_CERT_ALTNAME_INVALID')); (client.authorizationError === 'ERR_TLS_CERT_ALTNAME_INVALID'));
client.destroy(); client.destroy();

View File

@ -37,8 +37,8 @@ deepStrictEqual(translatePeerCertificate({ issuerCertificate: '' }),
deepStrictEqual(translatePeerCertificate({ issuerCertificate: null }), deepStrictEqual(translatePeerCertificate({ issuerCertificate: null }),
{ issuerCertificate: null }); { issuerCertificate: null });
deepStrictEqual( deepStrictEqual(
translatePeerCertificate({ issuerCertificate: { subject: certString } }), translatePeerCertificate({ issuerCertificate: { subject: certString } }),
{ issuerCertificate: { subject: certObject } }); { issuerCertificate: { subject: certObject } });
{ {
const cert = {}; const cert = {};
@ -51,5 +51,5 @@ deepStrictEqual(translatePeerCertificate({ infoAccess: '' }),
deepStrictEqual(translatePeerCertificate({ infoAccess: null }), deepStrictEqual(translatePeerCertificate({ infoAccess: null }),
{ infoAccess: null }); { infoAccess: null });
deepStrictEqual( deepStrictEqual(
translatePeerCertificate({ infoAccess: 'OCSP - URI:file:///etc/passwd' }), translatePeerCertificate({ infoAccess: 'OCSP - URI:file:///etc/passwd' }),
{ infoAccess: { 'OCSP - URI': ['file:///etc/passwd'] } }); { infoAccess: { 'OCSP - URI': ['file:///etc/passwd'] } });

View File

@ -10,14 +10,16 @@ const FILE_NAME = 'node_trace.1.log';
common.refreshTmpDir(); common.refreshTmpDir();
process.chdir(common.tmpDir); process.chdir(common.tmpDir);
const proc_no_categories = cp.spawn(process.execPath, const proc_no_categories = cp.spawn(
[ '--trace-events-enabled', '--trace-event-categories', '""', '-e', CODE ]); process.execPath,
[ '--trace-events-enabled', '--trace-event-categories', '""', '-e', CODE ]
);
proc_no_categories.once('exit', common.mustCall(() => { proc_no_categories.once('exit', common.mustCall(() => {
assert(!common.fileExists(FILE_NAME)); assert(!common.fileExists(FILE_NAME));
const proc = cp.spawn(process.execPath, const proc = cp.spawn(process.execPath,
[ '--trace-events-enabled', '-e', CODE ]); [ '--trace-events-enabled', '-e', CODE ]);
proc.once('exit', common.mustCall(() => { proc.once('exit', common.mustCall(() => {
assert(common.fileExists(FILE_NAME)); assert(common.fileExists(FILE_NAME));

View File

@ -7,15 +7,15 @@ const tty = require('tty');
assert.throws(() => { assert.throws(() => {
new tty.WriteStream(-1); new tty.WriteStream(-1);
}, common.expectsError({ }, common.expectsError({
code: 'ERR_INVALID_FD', code: 'ERR_INVALID_FD',
type: RangeError, type: RangeError,
message: '"fd" must be a positive integer: -1' message: '"fd" must be a positive integer: -1'
}) })
); );
const err_regex = common.isWindows ? const err_regex = common.isWindows ?
/^Error: EBADF: bad file descriptor, uv_tty_init$/ : /^Error: EBADF: bad file descriptor, uv_tty_init$/ :
/^Error: EINVAL: invalid argument, uv_tty_init$/; /^Error: EINVAL: invalid argument, uv_tty_init$/;
assert.throws(() => { assert.throws(() => {
let fd = 2; let fd = 2;
// Get first known bad file descriptor. // Get first known bad file descriptor.
@ -28,9 +28,9 @@ assert.throws(() => {
assert.throws(() => { assert.throws(() => {
new tty.ReadStream(-1); new tty.ReadStream(-1);
}, common.expectsError({ }, common.expectsError({
code: 'ERR_INVALID_FD', code: 'ERR_INVALID_FD',
type: RangeError, type: RangeError,
message: '"fd" must be a positive integer: -1' message: '"fd" must be a positive integer: -1'
}) })
); );

View File

@ -217,7 +217,7 @@ const formatTests = {
path: '/node' path: '/node'
}, },
// greater than or equal to 63 characters after `.` in hostname // greater than or equal to 63 characters after `.` in hostname
[`http://www.${'z'.repeat(63)}example.com/node`]: { [`http://www.${'z'.repeat(63)}example.com/node`]: {
href: `http://www.${'z'.repeat(63)}example.com/node`, href: `http://www.${'z'.repeat(63)}example.com/node`,
protocol: 'http:', protocol: 'http:',
@ -254,5 +254,5 @@ for (const u in formatTests) {
`wonky format(${u}) == ${expect}\nactual:${actual}`); `wonky format(${u}) == ${expect}\nactual:${actual}`);
assert.strictEqual(actualObj, expect, assert.strictEqual(actualObj, expect,
`wonky format(${JSON.stringify(formatTests[u])}) == ${ `wonky format(${JSON.stringify(formatTests[u])}) == ${
expect}\nactual: ${actualObj}`); expect}\nactual: ${actualObj}`);
} }

View File

@ -372,8 +372,8 @@ const relativeTests2 = [
'https://user:password@example.com', 'https://user:password@example.com',
'https://user:password@example.com/foo'], 'https://user:password@example.com/foo'],
// No path at all // No path at all
['#hash1', '#hash2', '#hash1'] ['#hash1', '#hash2', '#hash1']
]; ];
relativeTests2.forEach(function(relativeTest) { relativeTests2.forEach(function(relativeTest) {
const a = url.resolve(relativeTest[1], relativeTest[0]); const a = url.resolve(relativeTest[1], relativeTest[0]);

View File

@ -30,7 +30,7 @@ assert.strictEqual(b.a(), 'a');
assert.strictEqual(b.b(), 'b'); assert.strictEqual(b.b(), 'b');
assert.strictEqual(b.constructor, B); assert.strictEqual(b.constructor, B);
// two levels of inheritance // two levels of inheritance
function C() { function C() {
B.call(this, 'b'); B.call(this, 'b');
this._c = 'c'; this._c = 'c';
@ -83,9 +83,9 @@ assert.strictEqual(e.constructor, E);
assert.throws(function() { assert.throws(function() {
inherits(A, {}); inherits(A, {});
}, common.expectsError({ }, common.expectsError({
code: 'ERR_INVALID_ARG_TYPE', code: 'ERR_INVALID_ARG_TYPE',
type: TypeError, type: TypeError,
message: 'The "superCtor.prototype" property must be of type function' message: 'The "superCtor.prototype" property must be of type function'
}) })
); );
assert.throws(function() { assert.throws(function() {
@ -94,8 +94,8 @@ assert.throws(function() {
assert.throws(function() { assert.throws(function() {
inherits(null, A); inherits(null, A);
}, common.expectsError({ }, common.expectsError({
code: 'ERR_INVALID_ARG_TYPE', code: 'ERR_INVALID_ARG_TYPE',
type: TypeError, type: TypeError,
message: 'The "ctor" argument must be of type function' message: 'The "ctor" argument must be of type function'
}) })
); );

View File

@ -76,13 +76,22 @@ assert.strictEqual(util.inspect({ 'a': { 'b': { 'c': 2 } } }, false, 1),
'{ a: { b: [Object] } }'); '{ a: { b: [Object] } }');
assert.strictEqual(util.inspect({ 'a': { 'b': ['c'] } }, false, 1), assert.strictEqual(util.inspect({ 'a': { 'b': ['c'] } }, false, 1),
'{ a: { b: [Array] } }'); '{ a: { b: [Array] } }');
assert.strictEqual(util.inspect(Object.create({}, assert.strictEqual(
{ visible: { value: 1, enumerable: true }, hidden: { value: 2 } })), util.inspect(
'{ visible: 1 }' Object.create(
{},
{ visible: { value: 1, enumerable: true }, hidden: { value: 2 } }
)
),
'{ visible: 1 }'
);
assert.strictEqual(
util.inspect(
Object.assign(new String('hello'), { [Symbol('foo')]: 123 }),
{ showHidden: true }
),
'{ [String: \'hello\'] [length]: 5, [Symbol(foo)]: 123 }'
); );
assert.strictEqual(util.inspect(Object.assign(new String('hello'),
{ [Symbol('foo')]: 123 }), { showHidden: true }),
'{ [String: \'hello\'] [length]: 5, [Symbol(foo)]: 123 }');
assert.strictEqual(util.inspect((new JSStream())._externalStream), assert.strictEqual(util.inspect((new JSStream())._externalStream),
'[External]'); '[External]');
@ -177,14 +186,14 @@ for (const showHidden of [true, false]) {
Uint32Array, Uint32Array,
Uint8Array, Uint8Array,
Uint8ClampedArray ].forEach((constructor) => { Uint8ClampedArray ].forEach((constructor) => {
const length = 2; const length = 2;
const byteLength = length * constructor.BYTES_PER_ELEMENT; const byteLength = length * constructor.BYTES_PER_ELEMENT;
const array = new constructor(new ArrayBuffer(byteLength), 0, length); const array = new constructor(new ArrayBuffer(byteLength), 0, length);
array[0] = 65; array[0] = 65;
array[1] = 97; array[1] = 97;
assert.strictEqual( assert.strictEqual(
util.inspect(array, true), util.inspect(array, true),
`${constructor.name} [\n` + `${constructor.name} [\n` +
' 65,\n' + ' 65,\n' +
' 97,\n' + ' 97,\n' +
` [BYTES_PER_ELEMENT]: ${constructor.BYTES_PER_ELEMENT},\n` + ` [BYTES_PER_ELEMENT]: ${constructor.BYTES_PER_ELEMENT},\n` +
@ -192,11 +201,11 @@ for (const showHidden of [true, false]) {
` [byteLength]: ${byteLength},\n` + ` [byteLength]: ${byteLength},\n` +
' [byteOffset]: 0,\n' + ' [byteOffset]: 0,\n' +
` [buffer]: ArrayBuffer { byteLength: ${byteLength} } ]`); ` [buffer]: ArrayBuffer { byteLength: ${byteLength} } ]`);
assert.strictEqual( assert.strictEqual(
util.inspect(array, false), util.inspect(array, false),
`${constructor.name} [ 65, 97 ]` `${constructor.name} [ 65, 97 ]`
); );
}); });
// Now check that declaring a TypedArray in a different context works the same // Now check that declaring a TypedArray in a different context works the same
[ Float32Array, [ Float32Array,
@ -208,17 +217,17 @@ for (const showHidden of [true, false]) {
Uint32Array, Uint32Array,
Uint8Array, Uint8Array,
Uint8ClampedArray ].forEach((constructor) => { Uint8ClampedArray ].forEach((constructor) => {
const length = 2; const length = 2;
const byteLength = length * constructor.BYTES_PER_ELEMENT; const byteLength = length * constructor.BYTES_PER_ELEMENT;
const array = vm.runInNewContext( const array = vm.runInNewContext(
'new constructor(new ArrayBuffer(byteLength), 0, length)', 'new constructor(new ArrayBuffer(byteLength), 0, length)',
{ constructor, byteLength, length } { constructor, byteLength, length }
); );
array[0] = 65; array[0] = 65;
array[1] = 97; array[1] = 97;
assert.strictEqual( assert.strictEqual(
util.inspect(array, true), util.inspect(array, true),
`${constructor.name} [\n` + `${constructor.name} [\n` +
' 65,\n' + ' 65,\n' +
' 97,\n' + ' 97,\n' +
` [BYTES_PER_ELEMENT]: ${constructor.BYTES_PER_ELEMENT},\n` + ` [BYTES_PER_ELEMENT]: ${constructor.BYTES_PER_ELEMENT},\n` +
@ -226,11 +235,11 @@ for (const showHidden of [true, false]) {
` [byteLength]: ${byteLength},\n` + ` [byteLength]: ${byteLength},\n` +
' [byteOffset]: 0,\n' + ' [byteOffset]: 0,\n' +
` [buffer]: ArrayBuffer { byteLength: ${byteLength} } ]`); ` [buffer]: ArrayBuffer { byteLength: ${byteLength} } ]`);
assert.strictEqual( assert.strictEqual(
util.inspect(array, false), util.inspect(array, false),
`${constructor.name} [ 65, 97 ]` `${constructor.name} [ 65, 97 ]`
); );
}); });
// Due to the hash seed randomization it's not deterministic the order that // Due to the hash seed randomization it's not deterministic the order that
// the following ways this hash is displayed. // the following ways this hash is displayed.
@ -443,9 +452,9 @@ assert.strictEqual(util.inspect(-0), '-0');
function BadCustomError(msg) { function BadCustomError(msg) {
Error.call(this); Error.call(this);
Object.defineProperty(this, 'message', Object.defineProperty(this, 'message',
{ value: msg, enumerable: false }); { value: msg, enumerable: false });
Object.defineProperty(this, 'name', Object.defineProperty(this, 'name',
{ value: 'BadCustomError', enumerable: false }); { value: 'BadCustomError', enumerable: false });
} }
util.inherits(BadCustomError, Error); util.inherits(BadCustomError, Error);
assert.strictEqual( assert.strictEqual(
@ -1039,18 +1048,18 @@ if (typeof Symbol !== 'undefined') {
assert.throws(() => { assert.throws(() => {
util.inspect.defaultOptions = null; util.inspect.defaultOptions = null;
}, common.expectsError({ }, common.expectsError({
code: 'ERR_INVALID_ARG_TYPE', code: 'ERR_INVALID_ARG_TYPE',
type: TypeError, type: TypeError,
message: 'The "options" argument must be of type object' message: 'The "options" argument must be of type object'
}) })
); );
assert.throws(() => { assert.throws(() => {
util.inspect.defaultOptions = 'bad'; util.inspect.defaultOptions = 'bad';
}, common.expectsError({ }, common.expectsError({
code: 'ERR_INVALID_ARG_TYPE', code: 'ERR_INVALID_ARG_TYPE',
type: TypeError, type: TypeError,
message: 'The "options" argument must be of type object' message: 'The "options" argument must be of type object'
}) })
); );
} }

View File

@ -32,8 +32,8 @@ assert.throws(getHiddenValue({}), errMessageIndex);
assert.throws(getHiddenValue({}, null), errMessageIndex); assert.throws(getHiddenValue({}, null), errMessageIndex);
assert.throws(getHiddenValue({}, []), errMessageIndex); assert.throws(getHiddenValue({}, []), errMessageIndex);
assert.deepStrictEqual( assert.deepStrictEqual(
binding.getHiddenValue({}, kArrowMessagePrivateSymbolIndex), binding.getHiddenValue({}, kArrowMessagePrivateSymbolIndex),
undefined); undefined);
assert.throws(setHiddenValue(), errMessageObj); assert.throws(setHiddenValue(), errMessageObj);
assert.throws(setHiddenValue(null, 'foo'), errMessageObj); assert.throws(setHiddenValue(null, 'foo'), errMessageObj);
@ -45,11 +45,11 @@ assert.throws(setHiddenValue({}, null), errMessageIndex);
assert.throws(setHiddenValue({}, []), errMessageIndex); assert.throws(setHiddenValue({}, []), errMessageIndex);
const obj = {}; const obj = {};
assert.strictEqual( assert.strictEqual(
binding.setHiddenValue(obj, kArrowMessagePrivateSymbolIndex, 'bar'), binding.setHiddenValue(obj, kArrowMessagePrivateSymbolIndex, 'bar'),
true); true);
assert.strictEqual( assert.strictEqual(
binding.getHiddenValue(obj, kArrowMessagePrivateSymbolIndex), binding.getHiddenValue(obj, kArrowMessagePrivateSymbolIndex),
'bar'); 'bar');
let arrowMessage; let arrowMessage;

View File

@ -16,7 +16,7 @@ const binding = process.binding('util');
next(); next();
}, },
(next) => { (next) => {
// Test with one call to the watchdog, one signal. // Test with one call to the watchdog, one signal.
binding.startSigintWatchdog(); binding.startSigintWatchdog();
process.kill(process.pid, 'SIGINT'); process.kill(process.pid, 'SIGINT');
waitForPendingSignal(common.mustCall(() => { waitForPendingSignal(common.mustCall(() => {
@ -26,7 +26,7 @@ const binding = process.binding('util');
})); }));
}, },
(next) => { (next) => {
// Nested calls are okay. // Nested calls are okay.
binding.startSigintWatchdog(); binding.startSigintWatchdog();
binding.startSigintWatchdog(); binding.startSigintWatchdog();
process.kill(process.pid, 'SIGINT'); process.kill(process.pid, 'SIGINT');
@ -39,7 +39,7 @@ const binding = process.binding('util');
})); }));
}, },
() => { () => {
// Signal comes in after first call to stop. // Signal comes in after first call to stop.
binding.startSigintWatchdog(); binding.startSigintWatchdog();
binding.startSigintWatchdog(); binding.startSigintWatchdog();
const hadPendingSignals1 = binding.stopSigintWatchdog(); const hadPendingSignals1 = binding.stopSigintWatchdog();

View File

@ -127,7 +127,7 @@ const objects = [
buf = buf.slice(32); buf = buf.slice(32);
const expectedResult = os.endianness() === 'LE' ? const expectedResult = os.endianness() === 'LE' ?
new Uint16Array([0xdead, 0xbeef]) : new Uint16Array([0xadde, 0xefbe]); new Uint16Array([0xdead, 0xbeef]) : new Uint16Array([0xadde, 0xefbe]);
assert.deepStrictEqual(v8.deserialize(buf), expectedResult); assert.deepStrictEqual(v8.deserialize(buf), expectedResult);
} }

View File

@ -32,8 +32,8 @@ if (process.argv[2] === 'child') {
const script = `process.send('${method}'); while(true) {}`; const script = `process.send('${method}'); while(true) {}`;
const args = method === 'runInContext' ? const args = method === 'runInContext' ?
[vm.createContext({ process })] : [vm.createContext({ process })] :
[]; [];
const options = { breakOnSigint: true }; const options = { breakOnSigint: true };
assert.throws(() => { vm[method](script, ...args, options); }, assert.throws(() => { vm[method](script, ...args, options); },

View File

@ -17,8 +17,8 @@ if (process.argv[2] === 'child') {
const script = `process.send('${method}'); while(true) {}`; const script = `process.send('${method}'); while(true) {}`;
const args = method === 'runInContext' ? const args = method === 'runInContext' ?
[vm.createContext({ process })] : [vm.createContext({ process })] :
[]; [];
const options = { breakOnSigint: true }; const options = { breakOnSigint: true };
for (let i = 0; i < listeners; i++) for (let i = 0; i < listeners; i++)

View File

@ -13,7 +13,7 @@ const wptToASCIITests = require('../fixtures/url-toascii.js');
{ {
const expectedError = common.expectsError( const expectedError = common.expectsError(
{ code: 'ERR_MISSING_ARGS', type: TypeError }, 2); { code: 'ERR_MISSING_ARGS', type: TypeError }, 2);
assert.throws(() => domainToASCII(), expectedError); assert.throws(() => domainToASCII(), expectedError);
assert.throws(() => domainToUnicode(), expectedError); assert.throws(() => domainToUnicode(), expectedError);
assert.strictEqual(domainToASCII(undefined), 'undefined'); assert.strictEqual(domainToASCII(undefined), 'undefined');

View File

@ -26,7 +26,7 @@ const failureTests = tests.filter((test) => test.failure).concat([
]); ]);
const expectedError = common.expectsError( const expectedError = common.expectsError(
{ code: 'ERR_INVALID_URL', type: TypeError }, 102); { code: 'ERR_INVALID_URL', type: TypeError }, 102);
for (const test of failureTests) { for (const test of failureTests) {
assert.throws( assert.throws(

View File

@ -11,7 +11,7 @@ const path = require('path');
const URL = require('url').URL; const URL = require('url').URL;
const { test, assert_equals } = require('../common/wpt'); const { test, assert_equals } = require('../common/wpt');
const additionalTestCases = require( const additionalTestCases = require(
path.join(common.fixturesDir, 'url-setter-tests-additional.js')); path.join(common.fixturesDir, 'url-setter-tests-additional.js'));
const request = { const request = {
response: require(path.join(common.fixturesDir, 'url-setter-tests')) response: require(path.join(common.fixturesDir, 'url-setter-tests'))

View File

@ -185,7 +185,7 @@ Object.keys(tests).forEach(function(file) {
// verify that the same exact buffer comes out the other end. // verify that the same exact buffer comes out the other end.
buf.on('data', function(c) { buf.on('data', function(c) {
const msg = `${file} ${chunkSize} ${ const msg = `${file} ${chunkSize} ${
JSON.stringify(opts)} ${Def.name} -> ${Inf.name}`; JSON.stringify(opts)} ${Def.name} -> ${Inf.name}`;
let ok = true; let ok = true;
const testNum = ++done; const testNum = ++done;
let i; let i;

View File

@ -19,5 +19,5 @@ tty.ref();
strictEqual(tty._handle.hasRef(), strictEqual(tty._handle.hasRef(),
true, 'tty_wrap: ref() ineffective'); true, 'tty_wrap: ref() ineffective');
tty._handle.close(common.mustCall(() => tty._handle.close(common.mustCall(() =>
strictEqual(tty._handle.hasRef(), strictEqual(tty._handle.hasRef(),
false, 'tty_wrap: not unrefed on close'))); false, 'tty_wrap: not unrefed on close')));

View File

@ -58,7 +58,7 @@ const spawn = require('child_process').spawn;
* deepest function is the only caller of os.loadavg(). * deepest function is the only caller of os.loadavg().
*/ */
const dtrace = spawn('dtrace', [ '-qwn', `syscall::getloadavg:entry/pid == ${ const dtrace = spawn('dtrace', [ '-qwn', `syscall::getloadavg:entry/pid == ${
process.pid}/{ustack(100, 8192); exit(0); }` ]); process.pid}/{ustack(100, 8192); exit(0); }` ]);
let output = ''; let output = '';

View File

@ -58,21 +58,21 @@ process.on('exit', function() {
fs.writeFileSync(filepathOne, 'hello'); fs.writeFileSync(filepathOne, 'hello');
assert.throws( assert.throws(
function() { function() {
fs.watchFile(filepathOne); fs.watchFile(filepathOne);
}, },
function(e) { function(e) {
return e.message === '"watchFile()" requires a listener function'; return e.message === '"watchFile()" requires a listener function';
} }
); );
assert.doesNotThrow( assert.doesNotThrow(
function() { function() {
fs.watchFile(filepathOne, function() { fs.watchFile(filepathOne, function() {
fs.unwatchFile(filepathOne); fs.unwatchFile(filepathOne);
++watchSeenOne; ++watchSeenOne;
}); });
} }
); );
setTimeout(function() { setTimeout(function() {
@ -85,27 +85,27 @@ process.chdir(testDir);
fs.writeFileSync(filepathTwoAbs, 'howdy'); fs.writeFileSync(filepathTwoAbs, 'howdy');
assert.throws( assert.throws(
function() { function() {
fs.watchFile(filepathTwo); fs.watchFile(filepathTwo);
}, },
function(e) { function(e) {
return e.message === '"watchFile()" requires a listener function'; return e.message === '"watchFile()" requires a listener function';
} }
); );
assert.doesNotThrow( assert.doesNotThrow(
function() { function() {
function a() { function a() {
fs.unwatchFile(filepathTwo, a); fs.unwatchFile(filepathTwo, a);
++watchSeenTwo; ++watchSeenTwo;
}
function b() {
fs.unwatchFile(filepathTwo, b);
++watchSeenTwo;
}
fs.watchFile(filepathTwo, a);
fs.watchFile(filepathTwo, b);
} }
function b() {
fs.unwatchFile(filepathTwo, b);
++watchSeenTwo;
}
fs.watchFile(filepathTwo, a);
fs.watchFile(filepathTwo, b);
}
); );
setTimeout(function() { setTimeout(function() {
@ -113,15 +113,15 @@ setTimeout(function() {
}, 1000); }, 1000);
assert.doesNotThrow( assert.doesNotThrow(
function() { function() {
function b() { function b() {
fs.unwatchFile(filenameThree, b); fs.unwatchFile(filenameThree, b);
++watchSeenThree; ++watchSeenThree;
}
fs.watchFile(filenameThree, common.mustNotCall());
fs.watchFile(filenameThree, b);
fs.unwatchFile(filenameThree, common.mustNotCall());
} }
fs.watchFile(filenameThree, common.mustNotCall());
fs.watchFile(filenameThree, b);
fs.unwatchFile(filenameThree, common.mustNotCall());
}
); );
setTimeout(function() { setTimeout(function() {
@ -137,12 +137,12 @@ setTimeout(function() {
}, 500); }, 500);
assert.doesNotThrow( assert.doesNotThrow(
function() { function() {
function a() { function a() {
++watchSeenFour; ++watchSeenFour;
assert.strictEqual(1, watchSeenFour); assert.strictEqual(1, watchSeenFour);
fs.unwatchFile(`.${path.sep}${filenameFour}`, a); fs.unwatchFile(`.${path.sep}${filenameFour}`, a);
}
fs.watchFile(filenameFour, a);
} }
fs.watchFile(filenameFour, a);
}
); );

View File

@ -11,7 +11,7 @@ const seeds = [];
for (let i = 0; i < REPETITIONS; ++i) { for (let i = 0; i < REPETITIONS; ++i) {
const seed = cp.spawnSync(process.execPath, [targetScript], const seed = cp.spawnSync(process.execPath, [targetScript],
{ encoding: 'utf8' }).stdout.trim(); { encoding: 'utf8' }).stdout.trim();
seeds.push(seed); seeds.push(seed);
} }

View File

@ -83,19 +83,19 @@ if (cluster.isMaster) {
// First worker should bind, second should err // First worker should bind, second should err
const socket3OnBind = const socket3OnBind =
isSecondWorker ? isSecondWorker ?
common.mustNotCall() : common.mustNotCall() :
common.mustCall(() => { common.mustCall(() => {
const port3 = socket3.address().port; const port3 = socket3.address().port;
assert.strictEqual(typeof port3, 'number'); assert.strictEqual(typeof port3, 'number');
process.send('success'); process.send('success');
}); });
// an error is expected only in the second worker // an error is expected only in the second worker
const socket3OnError = const socket3OnError =
!isSecondWorker ? !isSecondWorker ?
common.mustNotCall() : common.mustNotCall() :
common.mustCall((err) => { common.mustCall((err) => {
process.send(`socket3:${err.code}`); process.send(`socket3:${err.code}`);
}); });
const address = common.localhostIPv4; const address = common.localhostIPv4;
const opt1 = { address, port: 0, exclusive: false }; const opt1 = { address, port: 0, exclusive: false };
const opt2 = { address, port: common.PORT, exclusive: false }; const opt2 = { address, port: common.PORT, exclusive: false };

View File

@ -248,7 +248,7 @@ if (process.argv[2] === 'child') {
assert.strictEqual( assert.strictEqual(
code, 0, `Test at index ${testIndex code, 0, `Test at index ${testIndex
} should have exited with exit code 0 but instead exited with code ${ } should have exited with exit code 0 but instead exited with code ${
code} and signal ${signal}`); code} and signal ${signal}`);
}); });
}); });
} }

View File

@ -54,18 +54,18 @@ common.refreshTmpDir();
fs.writeFileSync(filepathOne, 'hello'); fs.writeFileSync(filepathOne, 'hello');
assert.doesNotThrow( assert.doesNotThrow(
function() { function() {
const watcher = fs.watch(filepathOne); const watcher = fs.watch(filepathOne);
watcher.on('change', function(event, filename) { watcher.on('change', function(event, filename) {
assert.strictEqual(event, 'change'); assert.strictEqual(event, 'change');
if (expectFilePath) { if (expectFilePath) {
assert.strictEqual(filename, 'watch.txt'); assert.strictEqual(filename, 'watch.txt');
} }
watcher.close(); watcher.close();
++watchSeenOne; ++watchSeenOne;
}); });
} }
); );
setImmediate(function() { setImmediate(function() {
@ -78,17 +78,17 @@ process.chdir(testDir);
fs.writeFileSync(filepathTwoAbs, 'howdy'); fs.writeFileSync(filepathTwoAbs, 'howdy');
assert.doesNotThrow( assert.doesNotThrow(
function() { function() {
const watcher = fs.watch(filepathTwo, function(event, filename) { const watcher = fs.watch(filepathTwo, function(event, filename) {
assert.strictEqual(event, 'change'); assert.strictEqual(event, 'change');
if (expectFilePath) { if (expectFilePath) {
assert.strictEqual(filename, 'hasOwnProperty'); assert.strictEqual(filename, 'hasOwnProperty');
} }
watcher.close(); watcher.close();
++watchSeenTwo; ++watchSeenTwo;
}); });
} }
); );
setImmediate(function() { setImmediate(function() {
@ -100,19 +100,19 @@ const testsubdir = fs.mkdtempSync(testDir + path.sep);
const filepathThree = path.join(testsubdir, filenameThree); const filepathThree = path.join(testsubdir, filenameThree);
assert.doesNotThrow( assert.doesNotThrow(
function() { function() {
const watcher = fs.watch(testsubdir, function(event, filename) { const watcher = fs.watch(testsubdir, function(event, filename) {
const renameEv = common.isSunOS || common.isAIX ? 'change' : 'rename'; const renameEv = common.isSunOS || common.isAIX ? 'change' : 'rename';
assert.strictEqual(event, renameEv); assert.strictEqual(event, renameEv);
if (expectFilePath) { if (expectFilePath) {
assert.strictEqual(filename, 'newfile.txt'); assert.strictEqual(filename, 'newfile.txt');
} else { } else {
assert.strictEqual(filename, null); assert.strictEqual(filename, null);
} }
watcher.close(); watcher.close();
++watchSeenThree; ++watchSeenThree;
}); });
} }
); );
setImmediate(function() { setImmediate(function() {

View File

@ -56,11 +56,11 @@ server.listen(common.PORT, '127.0.0.1', function() {
console.log( console.log(
`Socket: ${agent.sockets[addrString].length}/${ `Socket: ${agent.sockets[addrString].length}/${
agent.maxSockets} queued: ${ agent.maxSockets} queued: ${
agent.requests[addrString] ? agent.requests[addrString].length : 0}`); agent.requests[addrString] ? agent.requests[addrString].length : 0}`);
const agentRequests = agent.requests[addrString] ? const agentRequests = agent.requests[addrString] ?
agent.requests[addrString].length : 0; agent.requests[addrString].length : 0;
if (maxQueued < agentRequests) { if (maxQueued < agentRequests) {
maxQueued = agentRequests; maxQueued = agentRequests;

View File

@ -57,7 +57,7 @@ function test(environ, shouldWrite, section) {
if (shouldWrite) { if (shouldWrite) {
expectErr = expectErr =
`${section.toUpperCase()} ${child.pid}: this { is: 'a' } /debugging/\n${ `${section.toUpperCase()} ${child.pid}: this { is: 'a' } /debugging/\n${
section.toUpperCase()} ${child.pid}: num=1 str=a obj={"foo":"bar"}\n`; section.toUpperCase()} ${child.pid}: num=1 str=a obj={"foo":"bar"}\n`;
} }
let err = ''; let err = '';

Some files were not shown because too many files have changed in this diff Show More